函数原型 :
template<class _Policy_type,
class _Fty,
class... _ArgTypes> inline
future<typename result_of<
typename enable_if<_Is_launch_type<
_Policy_type>::value, _Fty>
::type(_ArgTypes...)>::type>
async(_Policy_type _Policy, _Fty&& _Fnarg,
_ArgTypes&&... _Args)
template<class _Fty,
class... _ArgTypes> inline
future<typename result_of<
typename enable_if<!_Is_launch_type<
typename decay<_Fty>::type>::value, _Fty>
::type(_ArgTypes...)>::type>
async(_Fty&& _Fnarg, _ArgTypes&&... _Args)
选项枚举:
enum class launch { // names for launch options passed to async
async = 0x1, //立即执行
deferred = 0x2, //调用get 或者 wait时才执行 (wait_for 或者 wait_until 不会触发)
any = async | deferred, //条件允许则async,否则 deferred
sync = deferred
};
状态枚举:
enum class future_status { // names for timed wait function returns
ready, //执行完成
timeout, //执行超时(wait_for)
deferred //还没执行
};
简单使用:
std::future<int> ff = std::async(std::launch::async, [](){return 10});
if (ff.valid())
{
std::cout<< ff.get()<<std::endl; //get函数只能调用一次,如果需要多次使用需要shared_future
}
if (ff.valid()) //此时返回false,ff已经处于无效状态
{
std::cout<< ff.get()<<std::endl;
}
调用成员函数void Test::doSomething(int a)
{
std::cout <<"dosomething "<<a<< std::endl;
}
void Test::Call()
{
if (!ff.valid())
{
ff = std::async(std::launch::async, &Test::doSomething, this,10);
}
}
private:
std::future<void> ff;
输出参数
std::promise<int> per;
std::future<int> hehe = per.get_future();
auto f = std::async(std::launch::async,
[](std::promise<int> &pp){pp.set_value(10);},
std::ref(per));
f.get();
std::cout << hehe.get() << std::endl;
getchar();