voidpromise_set_value(std::promise<int>& promise){ std::this_thread::sleep_for(std::chrono::seconds(1)); promise.set_value(100); // future would become ready after promise.set_value() }
intsum(int from, int to){ int ret = 0; for (int i = from; i < to; ++i) { ret += i; } return ret; }
intsum_with_multi_thread(int from, int to, size_t thread_num){ int count = to - from; int count_per_thread = thread_num > 0 ? count / thread_num : count; std::vector<std::future<int>> v; for (; from < to; from += count_per_thread) { v.push_back(std::async( sum, from, from + count_per_thread > to ? to : from + count_per_thread)); }
int ret = 0; for (auto &f : v) { ret += f.get(); } return ret; }
If we have to get the result from the future such as inside multiple threads, we can request for help from std::shared_future whose feature is a little similar to std::shared_ptr.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<future> #include<iostream>
intmain(){ std::promise<int> promise;
std::shared_future<int> shared_future1 = promise.get_future(); // The initialization of `shared_future1` is actually equivalent to the code below: // std::future<int> future = promise.get_future(); // std::shared_future<int> shared_future1 = std::move(future); std::shared_future<int> shared_future2 = future1;