Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to call shared_future::get() multiple times on the same instance in the same thread?

Tags:

c++

boost

future

I can find neither direct confirmation nor refutation on the matter. All answers seem to address the "access from multiple threads" aspect, rather than repetitive access itself.

Does the standard define the behavior for std::shared_future? What about boost::shared_future?

like image 660
vines Avatar asked Jun 25 '19 14:06

vines


2 Answers

Per cppreference in std::shared_future<T>::valid

Unlike std::future, std::shared_future's shared state is not invalidated when get() is called.

Which makes sense. If it wasn't the case then you couldn't have multiple threads be able to call get. We can further back this up by looking at the standard. In [futures.unique.future]/15 they explicitly state get only works once with

releases any shared state ([futures.state]).

while in [futures.shared.future]/18 it states no such thing so the state is still valid after get is called.


boost::shared_future has the same behavior. Per the reference get has no text stating it invalidates the shared state on a call to get so you can call it multiple times.

like image 100
NathanOliver Avatar answered Oct 10 '22 02:10

NathanOliver


AFAIK this is legal. std::shared_future<T>::get() says:

The behavior is undefined if valid() is false before the call to this function.

Going to std::shared_future<T>::valid() it says:

Checks if the future refers to a shared state.

...

Unlike std::future, std::shared_future's shared state is not invalidated when get() is called.

Which would make multiple get() calls from the same thread and on the same instance valid.

like image 35
Hatted Rooster Avatar answered Oct 10 '22 02:10

Hatted Rooster