Is calling wait() on a std::future multiple times and from multiple threads safe?
c++, c++11, multithreading
Solution
Getting a future from a promise starts it off with valid()==true. As far as I can see only future::get() sets valid() back to false. Is this assumption correct?
It can also become invalid by move-assigning an invalid future to it, or by moving the future so its shared state transfers to a different object. It can't become invalid just by waiting though.
Can I call the wait() family of functions as often as I want?
Yes.
Will calls to wait() after the promise's value has been set return immediately?
Yes (it might involve locking a mutex or spinlock to check if the state is ready, then returning, so might involve a small wait to acquire the lock)
Can I call them from multiple threads?
Yes.
`wait()` is a const member function, so the library is required to ensure it can be called on a single future object from multiple threads without any user-provided synchronisation.
Problem
I'm trying to determine when I can safely call `wait()` on `std::future` and `std::shared_future`. I never call `get()` on the `future`, and the `future` is set ready from a call to its corresponding promise's `set_value()` method. I want to wait on this `future` (using `wait()`, `wait_for()`, `wait_until()`) from multiple threads. I also want calls to `wait()` after `promise::set_value()` has been called to return immediately. From http://www.cplusplus.com/reference/future/future/wait/ Calling this member function on a future object that is not valid, produces undefined behavior Getting a `future` from a `promise` starts it off with `valid()==true`. As far as I can see only `future::get()` sets `valid()` back to false. Is this assumption correct? Can I call the `wait()` family of functions as often as I want? Will calls to `wait()` after the promise's value has been set return immediately? Can I call them from multiple threads?