c++futurefolly

Is .thenValue() blocking?


In a lot of places I find something like :

std::move(A).thenValue(B)

Is thenValue() blocking on the future "A". I read through Folly documentation but couldn't understand it. https://github.com/facebook/folly/blob/master/folly/docs/Futures.md


Solution

  • No, it is not blocking. Conceptually, you can think of the signature like this (though this is not the actual signature):

    template <typename T>
    template <typename TResult>
    Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
    

    The basic idea is that if the future represented by std::move(A) succeeds, the passed callback (B) will be executed, passing in the value that the A future produced. The callback's return value becomes the result of the future returned by thenValue().

    If you're a visual person (like me) then perhaps labeling parts of the signature will help:

    template <typename T>
    template <typename TResult>
    Future<TResult> Future<T>::thenValue(std::function<TResult(T&&)> callback) { ... }
    ^^^^^^^^^^^^^^^ ^^^^^^^^^                                        ^^^^^^^^
           3            1                                                2
    
    1. The future you are invoking thenValue on.
    2. The callback function you pass to thenValue.
    3. The future returned by thenValue.

    When (1) has a successful result, (2) is invoked with that result. When (2) returns, (3) produces the return value of (2).

    The future (3) is constructed synchronously, but the callback (2) is invoked asynchronously.