Pass values between threads - C++ Patterns
← Patterns

Pass values between threads

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

Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.

C++ Patterns created by Joseph Mansfield