🐭 std::future 与 std::promise
对于异步任务来说,std::future 是给任务调用方用来查询结果的,std::promise 是给任务执行方来填充结果的。它们之间通过一个「shared state」联系在一起,进而完成结果数据的写入与读出。
std::future 操作图解:
代码示例 :
#include <algorithm>#include <future>#include <iostream>#include <numeric>#include <thread>#include <vector>void accumulate(std::vector<int>::iterator first, std::vector<int>::iterator last,std::promise<int> promise) {int sum = std::accumulate(first, last, 0);promise.set_value(sum);}int main() {// using promise<int> to transmit a result between threads// 1. the result is not store in the std::promise nor std::future, since:// - callee maybe destroyed before caller calls std::future::get()// - the std::future maybe copied or moved in caller side// 2. there must be a shared state between std::promise and std::future// - we can set value through std::promise// - and get value through std::futurestd::vector<int> nums = {1, 2, 3, 4, 5, 6};std::promise<int> promise;std::future<int> future = promise.get_future();std::thread thread(accumulate, nums.begin(), nums.end(), std::move(promise));std::cout << "result = " << future.get() << '\n'; // result = 21thread.join(); // don't forget to join the std::threadreturn 0;}
🐂 std::future 及其析构
在 C++ 中 std::thread 与 std::future 都是异步任务对应的操作系统软件线程的一个抽象。但是析构一个 joinable 的 std::thread 会导致程序异常结束,析构一个 std::future 似乎是一个正常的操作。
这是因为 std::future 的析构与上面提到的「shared state」的状态有关,对应于不同的「shared state」状态的 std::future 其析构方式不一样。
特殊析构操作 (会隐式调用 join),满足条件 1,2,3:
- 使用 std::async 创建的 std::future
- 线程启动策略为 std::launch::async
- 是最后一个 引用到 「shared state」的 std::future
正常析构操作 (只会减小引用计数):
- 除了上面说到的其他 std::future (包括 std::shared_future)
- 比如 std::packaged_task 创建的 std::future
- 比如 std::promise 创建的 std::future
代码示例 :
#include <future>#include <iostream>#include <thread>int sum(int a, int b) { return a + b; }int main() {// case 1: std::future special destruction (implicit call join)// 1. refers to a shared state that was created due to a call to std::async// 2. task’s launch policy is std::launch::async// 3. it is the last future referring to the shared state{// meet the conditions 1, 2, 3auto fut1 = std::async(std::launch::async, sum, 1, 2);std::cout << fut1.get() << '\n'; // 3} // before fut is destory, will implicit call join on the running thread// case 2: std::future (fut1) normal destruction// decrements the reference count inside the shared state{std::shared_future<int> fut3;{std::shared_future<int> fut2;{auto fut1 = std::async(std::launch::async, sum, 1, 2);fut2 = fut1.share(); // fut1 became invalid (onece)fut3 = fut2;} // fut2 is not the last std::future to the shared state, normal destory}std::cout << fut3.get() << '\n'; // 3} // fut3 is the last std::future to the shared state, special destoryreturn 0;}
:::tips 这里的 std::shared_future 与 std::shared_ptr 类似是基于引用计数的,能保证「shared state」一直可用,最后一个引用到「shared state」的 std::future 会析构自己,然后「shared state」也会析构 :::
🐯 总结
- 理解 std::future 的两种析构过程
- 理解 std::futrue 的几种创建方式
