17

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?

3
  • 1
    just clear the vector and create new ones.. seriously.. Commented Feb 3, 2016 at 10:06
  • 2
    @DavidHaim, what is it with everyone adding their answers as comments instead of answers? Commented Feb 3, 2016 at 10:43
  • 2
    because I ahve nothing smarter to say other than that Commented Feb 3, 2016 at 10:44

3 Answers 3

28

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 
Sign up to request clarification or add additional context in comments.

5 Comments

it should be my_promise = std::promise<int>() not my_promise = std::my_promise<int>(). Isn't it ?
You can also do std::promise<int>().swap(my_promise)
@user0000001 although it might actually be clearer to write my_promise = std::promise<int>()
make that my_promise = {};
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.
3

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

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.
3

Even simpler to do this. You won't have to touch the line if you later decide to change the value type.

my_promise = {}; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.