Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling wait() on a std::future multiple times and from multiple threads safe?

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?

like image 439
Prismatic Avatar asked Nov 22 '14 14:11

Prismatic


People also ask

Can multiple threads call the same function?

There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.

What are futures in c++?

Future. A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async. promise::get_future.


1 Answers

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.

like image 74
Jonathan Wakely Avatar answered Sep 30 '22 13:09

Jonathan Wakely