zengine-old/engine/3rdparty/zlib/test/04promise.cpp
2024-03-13 22:29:47 +08:00

50 lines
1.3 KiB
C++

#include <iostream>
#include <thread>
#include <future>
using namespace std;
void test1() {
promise<int> p;
future<int> f = p.get_future();
thread t1([&]() {
this_thread::sleep_for(chrono::milliseconds(1000));
p.set_value(12);
this_thread::sleep_for(chrono::milliseconds(1000));
});
t1.detach();
std::cout << "test1:: res:: " << f.get() << endl;
}
void test2() {
promise<int> p;
future<int> f = p.get_future();
shared_future<int> sf = f.share();
thread t1([&]() {
this_thread::sleep_for(chrono::milliseconds(1000));
p.set_value(12);
this_thread::sleep_for(chrono::milliseconds(1000));
});
t1.detach();
std::cout << "test2:: res:: " << sf.get() << sf .get() << endl;
}
void test3() {
auto fn = []()->int {
this_thread::sleep_for(chrono::milliseconds(1000));
return 12;
};
auto f = async(launch::async, fn);
packaged_task<int()> t(fn);
t();
std::cout << "test3:: res:: " << f.get() << t.get_future().get() << endl;
}
int main() {
test1();
test2();
test3();
//这里通过条件变量 | 信号量 + 共享变量就能实现
//用promise-future 感觉很浪费
std::cout << "promise size:: " << sizeof(promise<int>) <<
" future size:: " << sizeof(future<int>) <<
" shared_future size:: " << sizeof(shared_future<int>) << endl;
return 1;
}