liveBook · Manning

Then()

As explained in C++ Concurrency in Action, Second Edition

`then()` is a C++ Concurrency TS future operation that attaches a continuation to run after the future becomes ready.

`then()` attaches a continuation to a future, scheduling processing for when its result is ready instead of requiring the caller to wait. section 4.4.3

A continuation changes how the result and follow-on work are handled:

  • It receives a ready future as its argument. Adding it invalidates the original future and returns a new future for the continuation’s result; execution is on an unspecified thread. section 4.4.3
  • Chained continuations can return futures: `then()` unwraps the result, so the chain need not produce nested futures or block between asynchronous operations. section 4.4.4
std::experimental::future<int> find_the_answer;
auto fut=find_the_answer();
auto fut2=fut.then(find_the_question);
assert(!fut.valid());
assert(fut2.valid());

This short example shows the original future becoming invalid while the future returned by `then()` remains valid. section 4.4.3

Listing 4.20. A function to process user login with continuations
std::experimental::future<void> process_login(
    std::string const& username,std::string const& password)
{
    return spawn_async([=](){
        return backend.authenticate_user(username,password);
    }).then([](std::experimental::future<user_id> id){
        return backend.request_current_info(id.get());
    }).then([](std::experimental::future<user_data> info_to_display){
        try{
            update_display(info_to_display.get());
        } catch(std::exception& e){
            display_error(e);
        }
    });
}

The login flow chains authentication, requesting user data, and updating the display; the fully asynchronous variant is shown separately. section 4.4.4

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains future invalidation, continuation results, unspecified-thread execution, and unwrapping, but leaves thread choice to the implementation.
Examples
Demonstrates future validity changes and a login flow that chains authentication, user-data retrieval, and display updates.
What it assumes
Requires a future holding a task result and a continuation that processes that result.
What you can do after
Apply Concurrency TS futures to chain asynchronous operations without blocking between them.
How it connects
Connects futures and shared futures to asynchronous operations, including future unwrapping across chained continuations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.