c++11多線程 async、future、packaged_task、promise 第九講


(1)std::async、std::future創建後臺任務並返回
(2)std::packaged_task
(3)std::promise
(4)小結
一、std::async、std::future創建後臺任務並返回
希望線程返回一個結果;
std::async是一個函數模板,用來啓動一個異步任務,啓動起來一個異步任務後,
他返回一個std::future對象,std::future是一個類模板
什麼事是啓動一個異步任務呀?
就是自動創建一個線程,並開始執行對應的線程入口函數,它返回一個
std::future對象,這個對象中含有線程函數返回的結果(線程返回的結果)。
可以通過std::future對象的成員函數get()來獲取結果。
std::future提供了一種訪問異步操作結果的機制,這個結果沒辦法馬上獲得,
但是在這個線程執行完的時候,就可以獲取到結果了,future對象裏保存一個值,就是這個結果、

#include <future>
#include <list>
#include <map>
#include <mutex>
#include <thread>

int thread_fun()//線程入口函數
{
    cout<<"thread_fun start thread_id = "<<std::this_thread::get_id()<<endl;
    std::chrono::milliseconds dura(5000);//休息5秒
    std::this_thread::sleep_for(dura);//休息一定時長
    cout<<"thread_fun end thread_id = "<<std::this_thread::get_id()<<endl;
    
    return 5;
}

int main()
{
    //下列程序std::future對象get()成員函數等待線程執行結果並返回結果
    cout<<"main thread_id = "<<std::this_thread::get_id()<<endl;
    std::future<int> result = std::async(thread_fun);//創建一個線程,並開始執行
    綁定關係,流程不會卡在這裏
    cout<<"continue..."<<endl;
    int def = 0;

    cout<<result.get()<<endl;//會先卡在get()這裏,一直等到thread_fun執行完成,獲取到返回值,然後線程程序纔會繼續向下。
    
    //result.wait();//等待線程返回,本身不返回結果;
    cout<<"end  ..."<<endl;
    return 0;
    
}


class B
{
public:
    int thread_fun(int my_mun)//線程入口函數
    {
        cout<<my_mun<<endl;
        cout<<"thread_fun start thread_id = "<<std::this_thread::get_id()<<endl;
        std::chrono::milliseconds dura(5000);//休息5秒
        std::this_thread::sleep_for(dura);//休息一定時長
        cout<<"thread_fun end thread_id = "<<std::this_thread::get_id()<<endl;
        
        return 5;
    }
}


int main()
{
    A a1;
    int mun=12;
    //下列程序std::future對象get()成員函數等待線程執行結果並返回結果
    cout<<"main thread_id = "<<std::this_thread::get_id()<<endl;
    std::future<int> result = std::async(&A::thread_fun,&a,num);//創建一個線程,並開始執行
    綁定關係,流程不會卡在這裏
    cout<<"continue..."<<endl;
    int def = 0;

    cout<<result.get()<<endl;//會先卡在get()這裏,一直等到thread_fun執行完成,獲取到返回值,然後線程程序纔會繼續向下。
    
    //result.wait();//等待線程返回,本身不返回結果;
    cout<<"end  ..."<<endl;
    return 0;
    
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章