/*解决主线程和子线程后期同步的问题 类似于windows中的事件*/
#include "iostream"
#include "future"
#include "thread"
using namespace std;
int main(void)
{
promise<int>proms;//构建一个承若
auto& fut = proms.get_future();//用自动变量接收这个承诺
thread t1([&fut/*捕获承诺*/](void)->void
{
wcout << "doing sth.........." << endl;
wcout << "waiting for food" << endl;
wcout << "got " << fut.get()/*等待食物,此刻子线程阻塞在这里*/ << "food" << endl;
});
this_thread::sleep_for(chrono::seconds(10));//主线程暂时休眠10s
proms.set_value(100);//主线程提供食物,子线程接着运行,不然子线程在上面的fut等待
t1.join();//主线程等待子线程一起结束,子线程不结束主线程不结束
wcout << "fnish" << endl;
return 0;
}
//--------------------------------------------------------async 异步调用函数 封装了复杂的c++线程创建等细节--------------------------------------
#include<iostream>
#include<future> //C11新特性
using namespace std;
int bar(int num)
{
for (int i = 0; i < num; ++i)
{
this_thread::sleep_for(chrono::microseconds(1000));
cout << "X" << endl;
}
return 1;
}
int main(void)
{
cout << "main thread begin to exute" << endl;
future<int>fut = async(bar, 10); //作为函数bar的入参 通过函数的返回,作为同步点
cout << "sub thread begin to exute" << endl;
int result = fut.get(); //子线程 主线程同步 子线程没执行完,主线程会在这里等
cout << "got fut:" <<result<< endl;
return 0;
}