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

2

10

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?

Dawnedawson answered 25/6, 2019 at 14:15 Comment(0)
D
13

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.

Descend answered 25/6, 2019 at 14:22 Comment(2)
By the way, a curious observation on boost::futures. The link in the answer leads to docs on boost::fibers::shared_future, which (again!) seem to differ in behavior from boost::shared_future (which is defined in 'boost::thread').Dawnedawson
Ah, found! It is stated in the first example on shared_future: use3( ftr.get() ); // second use is definedDawnedawson
B
8

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.

Birth answered 25/6, 2019 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.