🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## std::async 、std::promise、std::packaged_task以及std::future之间有什么联系和区别 std::future是用于获取将来共享状态的运行结果或异常,相当于一个中间件,std::async 、std::promise、std::packaged_task都离不开它的帮助; std::packaged_task用于包装可调用目标,以便异步执行任务; std::promise用于设置共享状态的值,可以用于线程间交流,这个是比较特殊的。 std::async是最优雅地方式启动任务异步执行;在多数情况下,**建议使用asyn开启异步任务**,而不是使用packaged_task方式。 ## future 放到 thread 中执行 ``` #include <iostream> #include <future> #include <thread> int add(int a, int b) { std::this_thread::sleep_for(std::chrono::seconds(2)); return a + b; } int main() { std::packaged_task<int(int, int)> f(add); std::future<int> future = f.get_future(); std::thread(std::move(f), 1, 2).detach(); int i = future.get(); std::cout << i; return 0; } ``` ## std::async ``` #include <future> #include <iostream> #include <Windows.h> int main() { std::function<int(int, int)> f = [](int a, int b) { Sleep(10000); return a + b; }; std::future<int> res = std::async(f, 1, 2); std::cout << "--------------------"; // 阻塞,直到 res 能返回结果 std::cout << res.get(); std::cout << "=========="; return 0; } ``` ## task_lambda ``` #include <iostream> #include <cmath> #include <thread> #include <future> #include <functional> void task_lambda() { std::packaged_task<int(int, int)> task([](int a, int b) { return a + b; }); std::future<int> result = task.get_future(); task(2, 9); std::cout << "task_lambda:\t" << result.get() << '\n'; } int main() { task_lambda(); } ``` ## task_bind ``` #include <iostream> #include <cmath> #include <thread> #include <future> #include <functional> // unique function to avoid disambiguating the std::pow overload set int f(int x, int y) { return x + y; } void task_bind() { // 也可使用 // std::packaged_task<int()> task([] { return f(2, 11); }); std::packaged_task<int()> task(std::bind(f, 2, 11)); std::future<int> result = task.get_future(); task(); std::cout << "task_bind:\t" << result.get() << '\n'; } int main() { task_lambda(); // task_bind(); // task_thread(); } ``` ## task_thread ``` #include <iostream> #include <cmath> #include <thread> #include <future> #include <functional> // unique function to avoid disambiguating the std::pow overload set int f(int x, int y) { return x + y; } void task_thread() { std::packaged_task<int(int, int)> task(f); std::future<int> result = task.get_future(); std::thread task_td(std::move(task), 2, 10); task_td.join(); std::cout << "task_thread:\t" << result.get() << '\n'; } int main() { task_thread(); } ```