std::future
From cppreference.com
Defined in header <future>
|
||
template< class T > class future; |
(1) | (since C++11) |
template< class T > class future<T&>; |
(2) | (since C++11) |
template<> class future<void>; |
(3) | (since C++11) |
The class template std::future defines an asynchronous return object, which references a shared state and does not share it with any other asynchronous return objects (as opposed to std::shared_future). Whenever a task is executed asynchronously (via std::async, std::packaged_task, or std::promise), a shared state is created, which is initially empty, but eventually holds the return value or the exception thrown by the task. An instance of std::future may be created that references that shared state. This instance can be used by another thread to check if the asynchronous task completed, to wait for completion, and to read the return value or the exception stored in the shared state once ready.
Contents |
[edit] Member functions
constructs the future object (public member function) | |
destructs the future object (public member function) | |
moves the future object (public member function) | |
returns a shared_future referring to the result associated to *this (public member function) | |
Getting the result | |
returns the result (public member function) | |
State | |
checks if the result is available (public member function) | |
waits for the result to become available (public member function) | |
waits for the result, returns if it is not available for the specified timeout duration (public member function) | |
waits for the result, returns if it is not available until specified time point has been reached (public member function) |
[edit] Example
#include <iostream> #include <future> #include <thread> int main() { // future from a packaged_task std::packaged_task<int()> task([](){return 7;}); // wrap the function std::future<int> f1 = task.get_future(); // get a future std::thread(std::move(task)).detach(); // launch on a thread // future from an async() std::future<int> f2 = std::async(std::launch::async, [](){return 8;}); // future from a promise std::promise<int> p; std::future<int> f3 = p.get_future(); std::thread( [](std::promise<int>& p){ p.set_value(9); }, std::ref(p) ).detach(); std::cout << "Waiting..."; f1.wait(); f2.wait(); f3.wait(); std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; }
Output:
Waiting...Done! Results are: 7 8 9
[edit] See also
(C++11) |
provides a facility to launch a function in a new thread and acquire its return value asynchronously (function template) |
(C++11) |
waits for a value that is set asynchronously. The internal state is shared among several objects (class template) |