为什么C++11引入std::future和std::promise?c++11创建了线程以后,我们不能直接从thread.join()得到结果,必须定义一个变量,在线程执行时,对这个变量赋值,然后执行join(),过程相对繁琐。
thread库提供了future用来访问异步操作的结果。std::promise用来包装一个值将数据和future绑定起来,为获取线程函数中的某个值提供便利,取值是间接通过promise内部提供的future来获取的,也就是说promise的层次比future高。
#include <iostream>
#include <type_traits>
#include <future>
#include <thread>
using
namespace
std;
int
main() { std::promise<
int>
promiseParam; std::thread t([](std::promise<
int>&
p) { std::this_thread::sleep_for(std::chrono::seconds(
10));
//
线程睡眠10s p.set_value_at_thread_exit(
4);
// }, std::
ref
(promiseParam)); std::future<
int> futureParam =
promiseParam.get_future(); auto r = futureParam.
get();
//
线程外阻塞等待 std::cout << r <<
std::endl;
return
0
; }
上述程序执行到futureParam.get()时,有两个线程,新开的线程正在睡眠10s,而主线程正在等待新开线程的退出值,这个操作是阻塞的,也就是说std::future和std::promise某种程度也可以做为线程同步来使用。
std::packaged_task包装一个可调用对象的包装类(如function,lambda表达式(C++11之lambda表达式),将函数与future绑定起来。std::packaged_task与std::promise都有get_future()接口,但是std::packaged_task包装的是一个异步操作,而std::promise包装的是一个值。
#include <iostream>
#include <type_traits>
#include <future>
#include <thread>
using
namespace
std;
int
main() { std::packaged_task<
int()>
task([]() { std::this_thread::sleep_for(std::chrono::seconds(
10));
//
线程睡眠10s
return
4
; }); std::thread t1(std::
ref
(task)); std::future<
int> f1 =
task.get_future(); auto r = f1.
get();
//
线程外阻塞等待 std::cout << r <<
std::endl;
return
0
; }
而std::async比std::promise, std::packaged_task和std::thread更高一层,它可以直接用来创建异步的task,异步任务返回的结果也保存在future中。std::async的原型:
async( std::launch policy, Function&& f, Args&&... args );
std::launch policy有两个,一个是调用即创建线程(std::launch::async),一个是延迟加载方式创建线程(std::launch::deferred),当掉使用async时不创建线程,知道调用了future的get或者wait时才创建线程。之后是线程函数和线程参数。
#include <iostream>
#include <future>
#include <thread>
int
main() {
//
future from a packaged_task std::packaged_task<
int()>
task([]() { std::cout <<
“
packaged_task started
” <<
std::endl;
return
7; });
//
wrap the function std::future<
int> f1 = task.get_future();
//
get a future std::thread(std::move(task)).detach();
//
launch on a thread
//
future from an async() std::future<
int> f2 =
std::async(std::launch::deferred, []() { std::cout <<
“
Async task started
” <<
std::endl;
return
8
; });
//
future from a promise std::promise<
int>
p; std::future<
int> f3 =
p.get_future(); std::thread([&p] { p.set_value_at_thread_exit(
9
); }).detach(); f1.wait(); f2.wait(); f3.wait(); std::cout <<
“
Done!\nResults are:
” << f1.
get() <<
‘
‘ << f2.
get() <<
‘
‘ << f3.
get() <<
‘
\n
’
; }