C++Promise函數

Promise內部會創建一個shared state是用來放一個相應的類型的值或是一個異常,並可被future object 取其數據當線程結果ios

promise是在造成成果後纔將結果放進shared state中。因此不會發生讀和寫的併發操做promise

#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <exception>
#include <random>//隨機數類
#include <chrono>//時間處理類
#include <stdexcept>//標準異常類
#include <functional>//STL 定義運算函數(代替運算符)
#include <utility>//STL 通用模板類
using namespace std;

void toSomething(promise<string> &p)
{
    try{
        cout << "read char ('x' for exception):";
        //char c = cin.get();
        char c;
        default_random_engine dre(time(NULL));
        uniform_int_distribution<int> id(0, 24);
        c = 'a' + id(dre);
        //this_thread::sleep_for(chrono::milliseconds(5000));
        if (c == 'x')
        {
            throw runtime_error(string("char ") + " read");
        }
        string s = string("char ") + c + " processed";
        //在主函數調用get()方法時線程會停滯(block)直到share state 成爲ready-當promise的set_value()或set_exception()執行後即是如此,也不意味promise的線程已經結束;
        //該線程可能仍執行着其餘語句,甚至儲存其餘結果放進其餘promise內。
        //若是想令shared state 在線程確實結束時變成ready-以確保線程的local object 及其餘材料在釋放前清除線程你應該使用set_value_at_thread_exit() and set_exception_at_thread_exit(),防止泄露
        p.set_value_at_thread_exit(move(s));
    }
    catch (const exception &e)
    {
        p.set_exception_at_thread_exit(current_exception());
    }
}

int main()
{
    try{
        promise<string>p;//在線程定義前定義一個promise object。promise內部會創建y一個shared state, 在這裏
        //是用來放一個相應的類型的值或是一個異常,並可被future object 取其數據當線程結果
        //這個promise隨後被傳給一個分離線程中運行的任務(task):
        thread t(toSomething, ref(p));//藉由ref() 確保promise以by reference(傳地址)方式傳遞,使其能夠被改變。
        t.detach();//將線程分離主線程,使其在後臺運行
        future<string> f(p.get_future());//定義一個用來取promise結果的future(),它與promise()是匹配的
        cout << "result: " << f.get() << endl;//獲取線程的結果

    }
    catch (const exception &e)
    {
        cerr << "EXCEPTION:" << e.what() << endl;
    }
    system("pause");
    return 0;
}
相關文章
相關標籤/搜索