C++Promise函數


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

promise是在形成成果后才將結果放進shared state中。所以不會發生讀和寫的並發操作

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

 


免責聲明!

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



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