C++ 异步多线程
用到 C++ future 库,代码如下:
#include <iostream>
#include <future>
#include <unistd.h>
using namespace std;
double f(double a,double b){
double c = a+b;
sleep(3);
return c;
}
int main(){
double a=1.0,b=2.1;
future<double> fu = async(f,a,b);
cout<<"..."<<endl;
cout<<"result:"<<fu.get()<<endl;
return 0;
}
编译方式:
g++ -std=c++11 async.cpp -lpthread -o demo
future 无法实现多个线程等待同一个异步线程结果,future 对象调用 get 后会转移控制权,导致只有一个线程可以获取异步线程的返回值,要解决这个问题可以用 shared_future,代码如下:
#include <iostream>
#include <future>
#include <unistd.h>
using namespace std;
double f(double a,double b){
double c = a+b;
sleep(3);
return c;
}
int main(){
double a=1.0,b=2.1;
shared_future<double> fu = async(f,a,b);
shared_future<double> c1 = async(f,a,fu.get());
shared_future<double> c2 = async(f,a,fu.get());
cout<<"..."<<endl;
cout<<"result:"<<c1.get()<<endl;
cout<<"result:"<<c2.get()<<endl;
cout<<"result:"<<fu.get()<<endl;
return 0;
}