概述
c++11引入了 async函数,使得C++中实现异步任务回调实现起来比较简单
该函数来自头文件 #include <future>
函数原型
template<class Function, class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>,
std::decay_t<Args>...>>
async(std::launch policy, Function&& f, Args&&... args);
template<class Function, class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>,
std::decay_t<Args>...>>
async(Function&& f, Args&&... args);
标准延迟函数
sleep_for
std::this_thread::sleep_for(std::chrono::seconds(1));
异步方式运行函数
该用法为简易用法,理解一下原理即可,其实复杂的写法其实是差不多的,掌握简易的用法就能搞定80%的事情了。
std::future<int> fut = std::async (calculate, value);
函数:async隐式生成了线程,并启动了线程</