Tutorial by Examples

The following example sets a promise to be consumed by another thread: { auto promise = std::promise<std::string>(); auto producer = std::thread([&] { promise.set_value("Hello World"); }); auto fut...
This code implements a version of std::async, but it behaves as if async were always called with the deferred launch policy. This function also does not have async's special future behavior; the returned future can be destroyed without ever acquiring its value. template<typename F> auto asyn...
std::packaged_task bundles a function and the associated promise for its return type: template<typename F> auto async_deferred(F&& func) -> std::future<decltype(func())> { auto task = std::packaged_task<decltype(func())()>(std::forward<F>(func)); aut...
If constraints for std::promise and std::future are not met an exception of type std::future_error is thrown. The error code member in the exception is of type std::future_errc and values are as below, along with some test cases: enum class future_errc { broken_promise = /* the t...
In the following naive parallel merge sort example, std::async is used to launch multiple parallel merge_sort tasks. std::future is used to wait for the results and synchronize them: #include <iostream> using namespace std; void merge(int low,int mid,int high, vector<int>&num)...
std::async: performs an asynchronous operation. std::future: provides access to the result of an asynchronous operation. std::promise: packages the result of an asynchronous operation. std::packaged_task: bundles a function and the associated promise for its return type.

Page 1 of 1