线程执行需要自己建线程,这个还好,但是如果有数据同步交互就麻烦点。比如常见的需求,线程异步执行下面这个耗时的函数,方法返回int传给主线程,主线程在未来某一步需要结果的时候等待,还要用condition_variable来阻塞等待。异步库并没有什么比较trick的东西,更像是语法糖,把线程常用的东西简单化。
int test(int a){
for (int i = 0; i < 10;i++){
this_thread::sleep_for(chrono::milliseconds(1000));//代替某些耗时方法
cout << ++a<<endl;
}
return a;
}
1.单纯用async和future
#include <future> // std::promise, std::future
int main(void)
{
future<int> ft = async(test,100);
this_thread::sleep_for(chrono::milliseconds(3000));
cout << "waiting result" << endl;
cout << "get result:"<<ft.get()<<endl;//阻塞等待结果,就两句话完成线程同步工作
getchar();
return 0;
}
2.shared_future 可以重复get的future。下面的例子吧多线程race更改为future完成的
#include <thread>
#include <future>
class TestThread
{
public:
TestThread(shared_future<bool> & sf) :sfuture(sf){}
void start(){
thread t(std::bind(&TestThread::run,this));
t.detach();
}
void run(){
cout << "test thread waits. id:" << std::this_thread::get_id()<<endl;
bool flg=sfuture.get();
cout << "test thread is racing:" << std::this_thread::get_id() << endl;
}
shared_future<bool> &sfuture;
};
int main(void)
{
cout << "main thread id:" << std::this_thread::get_id() << endl;
promise<bool> prom;
future<bool> ft=prom.get_future();
shared_future<bool> & sfuture = ft.share();
for (int i = 0; i < 10; i++){
TestThread testThread(sfuture);
testThread.start();
}
cout << "ready?" << endl;
this_thread::sleep_for(chrono::milliseconds(3000));
cout << "go!" << endl;
prom.set_value(true);
getchar();
return 0;
}
本文介绍了C++11异步库的使用,特别是future、promise和async的功能。future作为线程的代替品,简化了数据同步交互的复杂性。示例展示了如何使用async启动异步任务,并通过future获取结果,简化了传统的线程同步操作。同时提到了shared_future,它允许多次获取结果,进一步说明了异步库如何优雅地处理多线程竞争问题。
412

被折叠的 条评论
为什么被折叠?



