这个代码很简单不太详细讲解,future/promise 模型 想象成为线程间传递结果的通信信道。
#include <future>
int calculate()
{
return 123;
}
void testcalculate()
{
auto fut = async(calculate);
//auto fut = async(launch::async ,calculate); //创建一个线程
//auto fut = async(launch::deferred,calculate);//使用的当前
int res = fut.get();
cout << "the answer is " << res << endl;
}
结果:
the answer is 123
另一个例子:
#include <future>
#include <list>
#include <iostream>
#include <exception>
using namespace std;
thread::id func()
{
return this_thread::get_id();
}
int main()
{
cout << "starting 2 tasks" << endl;
cout << "- task1: process endless loop of memory consumption" << endl;
cout << "- task2: wait for <return> and then for task1" << endl;
auto f1 = async(func); // start task1() asynchronously (now or later or never)
//返回一个future<thread::id>对象 //async有两种启动策略 一是马上异步执行 launch::async 一是延迟到调用get 函数才异步执行 launch::deferred
cout << "\nwait for the end of task1: " << endl;
try
{
cout << f1.get(); //wait for task1() to finish (raises exception ifany)
//acquire the result
}
catch (const exception& e)
{
cerr << "EXCEPTION: " << e.what() << endl;
}
cin.get();
getchar();
return 0;
}
结果:
starting 2 tasks
- task1: process endless loop of memory consumption
- task2: wait for <return> and then for task1
wait for the end of task1:
7396