← Patterns

Pass values between threads

12345678910111213141516171819#include <future> #include <thread> void func(std::promise<int> result_promise) noexcept { result_promise.set_value(42); } int main() { std::promise<int> result_promise; std::future<int> result_future = result_promise.get_future(); std::thread t{func, std::move(result_promise)}; int result = result_future.get(); t.join(); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Use promises to communicate values between threads.

Description

On line 11 we create a std::promise, which provides a mechanism for passing objects asynchronously between threads. On line 12 we get a std::future<int> from that promise, representing an int value that will arrive at some point in the future. We then move the promise into a new thread (as promises cannot be copied).

On line 6, in the thread function, we set the value of the promise to the value that we wish to asynchronously communicate back to main.

On line 16, we call the future’s get function to try to get the promised return value. This function will block until there is a value (or an exception) available. When the value is available (that is, when the value of the promise has been set on line 6), it will be returned by get.

Contributors

  • Joseph Mansfield
  • Mark A. Gibbs

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share