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
provides a mechanism to access the result of asynchronous operations:
std::future
object to the creator of that asynchronous operation.std::future
. These methods may block if the asynchronous operation has not yet provided a value.std::future
.Note that std::future
references shared state that is not shared with any other asynchronous return objects (as opposed to std::shared_future).
#include <future> #include <iostream> #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 t(std::move(task)); // 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([&p]{ p.set_value_at_thread_exit(9); }).detach(); std::cout << "Waiting..." << std::flush; f1.wait(); f2.wait(); f3.wait(); std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; t.join(); }
Output:
Waiting...Done! Results are: 7 8 9[edit] Example with exceptions
#include <future> #include <iostream> #include <thread> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p] { try { // code that may throw throw std::runtime_error("Example"); } catch (...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); } catch (...) {} // set_exception() may throw too } }); try { std::cout << f.get(); } catch (const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); }
Output:
Exception from the thread: Example[edit] See also runs a function asynchronously (potentially in a new thread) and returns a std::future that will hold the result
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4