I have a program, which should in cycle launch 8 threads, which will return a value using std::promise
. So I think I need to create a vector of 8 promise
objects, get their future
s, and use these promise
s to return the values and then join
the threads with main
. The problem is this: on the next iteration I will create 8 more threads -- can i reuse the same promise
objects, or do I need to create 8 more? I haven't found any way to reuse them on the internet, but maybe I'm missing something obvious?
Note that the std::promise object is meant to be used only once.
A promise is an object that can store a value of type T to be retrieved by a future object (possibly in another thread), offering a synchronization point. On construction, promise objects are associated to a new shared state on which they can store either a value of type T or an exception derived from std::exception .
To reuse promises, simply reassign them.
std::promise<int> my_promise;
//use the promise
my_promise = std::promise<int>(); //now you have a new promise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With