目錄
1、promise
給線程傳遞參數和獲取異常。
2、成員函數
1)創建
Promise p; default構造函數,建立有個帶有shared state的promise
Promise p(allocator_arg,alloc); 建立一個shared state的promise,以alloc爲分配器
Promise p(rv); Move構造函數,建立一個新的promise,它取rv的狀態,並從rv手中移走shared state
P = rv Move assignment; move assign rv的狀態至p,如果他不是ready就儲存一個std::future_error異常並夾帶broken_promise
2)設置
P.set_value(val); 設val爲值並令狀態爲ready
P.set_value_at_thread_exit(val); 設val爲值並令狀態爲ready,在當前線程結束時
P.set_exception(e ); 設e爲異常並令狀態爲ready
P.set_exception_at_thread_exit(e); 設e爲異常並令狀態爲ready,在當前線程結束時
3)其他函數
P.~promise(); 釋放shared state,並且如果他不是ready就儲存一個std::future_error異常並夾帶broken_promise;
Swap(p1,p2); 互換p1和p2的狀態
P1.swap(p2); 互換p1和p2的狀態
P.get_future(); 產生一個future object用以取回shared state
3、測試
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
#include <functional>
#include <utility>
using namespace std;
void doSomething(promise<string>& p)
{
try {
cout << "read char ('x' for exception):";
char c = cin.get();
if (c == 'x') {
throw runtime_error(string("char ") + c + " read");
}
string s = string("char ") + c + " processed";
//設置值
p.set_value(move(s));
//設置值,並在線程結束後設置爲共享狀態
//p.set_value_at_thread_exit(move(s));
}
catch (...) {
//設置異常
p.set_exception(current_exception());//內容設置爲異常
//設置異常,並在線程結束後設置爲共享狀態
//p.set_exception_at_thread_exit(current_exception());
}
}
int main()
{
try {
//創建
promise<string> p;
//取走p的狀態,並將p恢復初始狀態
//promise<string> p1 = move(p);
thread t(doSomething, std::ref(p));
thread::id threadID = t.get_id();
t.detach();//分離線程
//取出異常或p值
future<string>f(p.get_future());
cout << "result: " << f.get() << endl;
/*
future<string>f 關聯的是promise的結果。
與f關聯線程的一些用法有差異。
f.get();不會等待線程結束
這裏 進行線程分離或線程等待。
*/
}
catch (const exception & e) {
cerr << "EXCEPTION: " << e.what() << endl;
}
catch (...) {
cerr << "EXCEPTION " << endl;
}
system("pause");
}