future
使用future等待一次性事件,它和async连用。
async
异步运行一个函数,可能在新的线程中。
// 使用futer等待一次性事件
// 使用async 启动异步任务并返回结果
#include <future>
#include <iostream>
#include <string>
#include <functional>
using namespace std;
int find_thr_answer_to_ltuae(int a)
{
this_thread::sleep_for(5s);
a++;
return a;
}
void do_other_stuff()
{
cout << "do something" << endl;
}
/* 使用async来讲参数传递给函数 */
struct X
{
void foo(int,const string&);
string bar(const string&);
};
X x;
// 调用p->foo(42,"hello") , p是&x
future<void> f1 = std::async(&X::foo,&x,42,"hello");
// 调用temp.bar("goodbye"),temp是x的副本
auto f2 = std::async(&X::bar,x,"goodbye");
struct Y
{
double operator()(double);
};
Y y;
// 调用temp(3.14),其中temp是从Y()移动构造的
auto f3 = std::async(Y(),3.14);
// 调用y(3.14);
auto f4 = std::async(ref(y),3.14);
class move_only
{
public:
move_only();
move_only(move_only&&); // 移动构造函数
move_only(move_only const &) = delete;
move_only& operator=(move_only&&);// 移动赋值
move_only& operator=(move_only const&) = delete;
void operator()();
};
// 调用tmp(),其中temp是从std::moev(move_only())构造的
auto f5 = std::async(move_only());
// 函数声明
X baz(X&);
// 调用baz(x)
std::async(baz,ref(x));
/* async调用函数的方式 */
// 1.std::launch::deferred 函数的调用会延迟,直到调用future.wait或者get
// 2.std::launch::async,启动单独的线程运行函数
// 3.std::launch::async | std::launch::deferred 默认,由具体实现来选择
auto f6 = async(std::launch::deferred,Y(),1.2);
int main()
{
future<int> answer = async(find_thr_answer_to_ltuae,1);
do_other_stuff();
cout << "answer is " << answer.get() << endl;
exit(0);
}