目录
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");
}