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 futures, and use these promises 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?
- 1just clear the vector and create new ones.. seriously..David Haim– David Haim2016-02-03 10:06:09 +00:00Commented Feb 3, 2016 at 10:06
- 2@DavidHaim, what is it with everyone adding their answers as comments instead of answers?Timo Türschmann– Timo Türschmann2016-02-03 10:43:20 +00:00Commented Feb 3, 2016 at 10:43
- 2because I ahve nothing smarter to say other than thatDavid Haim– David Haim2016-02-03 10:44:55 +00:00Commented Feb 3, 2016 at 10:44
Add a comment |
3 Answers
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 5 Comments
TheWaterProgrammer
it should be
my_promise = std::promise<int>() not my_promise = std::my_promise<int>(). Isn't it ?user0000001
You can also do
std::promise<int>().swap(my_promise)ljleb
@user0000001 although it might actually be clearer to write
my_promise = std::promise<int>()user1095108
make that
my_promise = {};Dhwani Katagade
A nitpick: This doesn't really reuse a promise. It abandons the shared state of the promise, just as if
~promise() had been called, and then moves in a new promise's shared state into the same memory allocation. Calling it recycling a promise might be more appropriate. See.std::promise is meant to be used only once, so I would suggest to either create this set of promises every time, or use other mechanisms to communicate between threads (like vector + mutex). You could also consider using std::async instead of creating threads.
1 Comment
user0000001
I don't see any issues in reusing an
std::promise. After all, it supports std::swap. Though, in OP's use case it would probably be easier to create a new set of promises.