Pass values between threads
This pattern is licensed under the CC0 Public Domain Dedication.
Use promises to communicate values between threads.
On line 11 we create a
provides a mechanism for passing objects asynchronously between
threads. On line 12 we get a
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
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