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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM