c++11の異步方法 及線程間通信


1. std::promise 可以用來在線程間提供數據傳遞。

std::future = std::promise.get_future()。

線程中可以對promise賦值std::promise.set_value。

賦值之后std::future.get()就會返回其他線程中設置的值。

 
#include <iostream>
#include <future>
#include <chrono>

std::promise<int> promis;
int main(int argc, const char * argv[]) {
    std::future<int> fuResult = promis.get_future();
    std::thread t([](){
        std::this_thread::sleep_for(std::chrono::seconds(10));
        promis.set_value(123);
    });
    t.detach();
    std::cout<<"detach..."<<std::endl;
    std::cout<<fuResult.get()<<std::endl;
    return 0;
}
#include "stdafx.h"
#include <iostream>
#include <future>
#include <chrono>
#include <string>

std::promise<std::string> promis;
int main()
{
    std::future<std::string> fuResult = promis.get_future();

    auto t_cb=[]() 
    {
        std::cout << "subThread start!"<<std::endl;
        std::chrono::milliseconds dur(10000);
        std::this_thread::sleep_for(dur);
        promis.set_value("value from subThread");
    };

    std::thread t(t_cb);
    t.detach();
    std::cout << "detach..." << std::endl;
    std::cout << fuResult.get() << std::endl;

    getchar();
    return 0;
}

 

2. std::packaged_task  可以包裹一個函數, 有點類似std::function,不同之處在於這個可以通過get_future返回std::future對象來獲取異步執行的函數結果。

 

#include "stdafx.h"
#include <iostream>
#include <future>
#include <chrono>
#include <string>

int main()
{
    std::packaged_task<int()> task([]() 
    {
        std::cout << "packaged_task start!"<<std::endl;
        std::chrono::milliseconds dur(10000);
        std::this_thread::sleep_for(dur);
        return 10000;
    });
    std::future<int> fuResult = task.get_future();
    std::thread t_task(std::move(task));
    t_task.detach();
    std::cout << "detach..." << std::endl;
    std::cout << fuResult.get() << std::endl;
    getchar();
    return 0;
}

3. std::async提供異步執行的方法,std::future = std::async(...), 函數執行完成后可以通過std::future.get()獲取到執行函數的返回值。

 

#include <iostream>
#include <future>
#include <chrono>

int main(int argc, const char * argv[]) 
{ std::future
<int> fuResult = std::async([]()
{ std::this_thread::sleep_for(std::chrono::seconds(
10)); return 1; }); std::cout<<"detach..."<<std::endl; std::cout<<fuResult.get()<<std::endl; return 0; }

 

多線程一----多線程的應用

多線程二----簡單線程管理

多線程三----數據競爭和互斥對象

多線程四----死鎖和防止死鎖

多線程五----unick_lock和once_flag

多線程六----條件變量

多線程七----線程間通信


免責聲明!

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



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