c++11 异步编程 std::async
知识点
std::future 获取异步函数调用的结果。
std::result_of 获取函数模板的返回类型。
std::async 用于创建异步任务,实际上就是创建一个线程执行相应任
std::launch::async, enable asynchronous evaluation 异步执行
std::launch::deferred, enable lazy evaluation 懒汉模式,获取结果时才执行(当调用get时,async才执行)
typename &&f 非模板参数里表示右值引用,模板参数中表示universal references 万能引用。
std::forward 完美转发 std::forward<T>()不仅可以保持左值或者右值不变,同时还可以保持const、Lreference、Rreference、validate等属性不变
#include <iostream> #include <future> #include <string> #include <mutex> template <typename F, typename... Args> static auto Async(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { return std::async( std::launch::async, std::bind(std::forward<F>(f), std::forward<Args>(args)...); } int main(int argc, const char **argv) { auto my_callback = [](){ std::cout << "This is test example" << std::endl; }; auto* callback = reinterpret_cast<std::function<void()>*>(&(my_callback)); Async([this, callback] { if (true) { (*callback)(); } }); return 0; }