简体   繁体   中英

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?

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.

Accessing a single future from multiple threads might lead to data race and undefined behaviour if at least one of them could perform a get() and no proper synchronisation would avoid such a situation.

Hence, if you need to access a future from multiple threads, you should better consider shared_future : "They also allow the value in the shared state to be retrieved multiple times once ready." They are thread safe as long as each thread accesses to the shared future using its own shared_future object.

Remark: My answer assumes that at some time a get() could occur, as the promise was not explicitely mentioned to be promise<void>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM