Namespaces
Variants

std::execution::associate

From cppreference.com
 
 
Execution control library
Concepts
Utility components
Execution contexts
Execution domains
Forward progress guarantee
Environments
    
    
    
Queries
Completion signatures
Pipeable sender adaptors
Coroutine utility
 
Defined in header <execution>
inline constexpr /* unspecified */ associate{};
(1) (since C++26)
(customization point object)
Call signature
execution::sender auto associate( execution::sender auto sndr,
                                  execution::scope_token auto token );
(2) (since C++26)

Ties a sender to an async scope, so that the scope can keep track of it: associate(sndr, token) tries to associate sndr with the scope that token refers to, and returns a sender that behaves like sndr but is counted by the scope for as long as it, or the operation made from it, exists.

An async scope exists so that a program can find out when all the work started under it has finished, and therefore when the resources that work uses can be destroyed. associate is the basic building block for that: it does not start anything. It registers the sender with the scope, and the registration lasts until the sender (or the operation state created by connecting it) is destroyed. spawn and spawn_future are built on the same idea, and associate is the one to use when the work should be started some other way, for example as part of a larger sender pipeline, but still has to be tracked by the scope.

associate is a pipeable sender adaptor: sndr | associate(token) is equivalent to associate(sndr, token).

Parameters

sndr - the sender to associate with the scope
token - a scope token (for example the one from counting_scope) that decides whether the sender is accepted into its scope and keeps track of it

Return value

A sender with the same completions as sndr. What it does depends on whether the scope accepted it:

  • Associated: the scope accepted the sender. The returned sender behaves exactly like sndr when connected and started, and the association lasts until the returned sender is destroyed or, once it is connected, until the resulting operation state is destroyed. It also has whatever effects the token adds to the sender (for example, counting_scope makes the sender respond to the scope's stop requests).
  • Unassociated: the scope did not accept the sender (for example, it is closed). The input sender is discarded and never connected or started, and the returned sender completes immediately with the stopped signal. Alternatively, the token may throw an exception, which then propagates out of associate.

associate(sndr, token) is ill-formed if sndr does not satisfy execution::sender or token does not satisfy execution::scope_token.

Customization point objects

The name execution::associate denotes a customization point object, which is a const function object of a literal semiregular class type. See CustomizationPointObject for details.

Details

  • Calling associate does not start the sender, and it is not expected to allocate.
  • The association ends only at the end of the destructor of the sender or of its operation state, not when the work completes. This is deliberate: when a scope has no associations left, it signals that the resources it protects can be destroyed, so the signal must not be given while the operation state could still touch them.
  • Connecting the sender to a receiver as an rvalue moves the association into the operation state and cannot fail. Connecting it as an lvalue makes a new association with the scope, which can fail in the same two ways: the connected operation then behaves like an unassociated sender and completes stopped, or the token throws and the exception propagates out of connect.
  • The returned sender is copyable if sndr is, and moves transfer the association. A copy has an association of its own, so copying an associated sender can produce an unassociated one, if the scope no longer accepts new work. Like a stateful function object, a copy is not guaranteed to behave exactly like the original.
  • The returned sender can be connected and started more than once if sndr can be, and only once otherwise.

Notes

  • To start the work immediately and not wait for it, use spawn. To start it and get a sender for its result, use spawn_future. Use associate when the sender will be started later, or as a part of something larger, and the scope still has to know it exists.
  • An associated sender that is never started still counts: it keeps the scope from being joined until it is destroyed.
  • The token's wrap function can change how the sender behaves. With counting_scope, associated senders are given the scope's stop token, so asking the scope to stop makes work that has not started yet complete with the stopped signal.

Example

A sender is associated with a scope. join on the scope cannot complete while the associated sender exists, and it completes once the sender has run and been destroyed. After the scope has been joined, associating a sender fails: the sender is dropped, and the associated one completes stopped without running it.
The standard header is not available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec, the reference implementation.

#include <chrono>
#include <execution>
#include <print>
#include <thread>

namespace ex = std::execution;

// An event loop on its own thread; the destructor finishes
// the loop so that the thread can be joined.
struct loop_thread
{
    ex::run_loop loop;
    std::jthread thread;

    loop_thread() : thread([this] { loop.run(); }) {}
    ~loop_thread() { loop.finish(); }
};

int main()
{
    using namespace std::chrono_literals;

    loop_thread worker;
    ex::counting_scope scope;

    auto work = ex::associate(
        ex::schedule(worker.loop.get_scheduler())
            | ex::then([] { std::this_thread::sleep_for(150ms); }),
        scope.get_token());

    bool joined = false;
    std::jthread joiner([&] { std::this_thread::sync_wait(scope.join()); joined = true; });

    std::this_thread::sleep_for(50ms);
    std::println("join still waiting while the sender exists: {}", !joined);

    std::this_thread::sync_wait(std::move(work));
    joiner.join();
    std::println("join finished after the sender ran: {}", joined);

    // The scope is joined now, so it no longer accepts work.
    bool ran = false;
    auto late = std::this_thread::sync_wait(
        ex::associate(ex::just() | ex::then([&] { ran = true; return 1; }), scope.get_token()));
    std::println("sender associated after the join ran: {}, completed stopped: {}",
                 ran, !late.has_value());
}

Output:

join still waiting while the sender exists: true
join finished after the sender ran: true
sender associated after the join ran: false, completed stopped: true

See also

eagerly launches the given sender within an asynchronous scope, returning immediately without waiting for it to finish
(customization point object)[edit]
eagerly starts a sender within an asynchronous scope and returns a sender that completes with its result, or stopped if the scope did not accept it
(customization point object)[edit]
differs from simple_counting_scope by adding support for cancellation
(class) [edit]