Namespaces
Variants

std::execution::spawn

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>
struct /* unspecified */ spawn_t;
(1) (since C++26)
inline constexpr /* unspecified */ spawn{};
(2) (since C++26)
(customization point object)
Call signatures
void spawn( execution::sender auto sndr,
            execution::scope_token auto token );
(3) (since C++26)
void spawn( execution::sender auto sndr,
            execution::scope_token auto token,
            /*queryable-object*/ auto env );
(4) (since C++26)

Starts a sender in the background and returns immediately, without waiting for it to finish. The work belongs to an async scope, which lets the program wait for all of it later: spawn(sndr, token) tries to associate sndr with the scope that token refers to and, if that succeeds, starts sndr right away.

spawn is for starting a number of independent tasks that is not known in advance, for example one per item in a container, one per incoming request, or one per event, when the code that starts them does not want to wait for each and has no sender to return. The scope keeps track of every task that has been spawned into it, so the program can wait for all of them to finish (with join on counting_scope) before destroying the resources the tasks use, which is what made fire-and-forget starts unsafe.

Parameters

sndr - the sender to start; see below for what it may complete with
token - a scope token (for example the one from counting_scope) that decides whether the work is accepted into its scope and keeps track of it while it runs
env - an optional queryable object that is joined into the environment the work sees (for example to choose an allocator or a stop token); the default is an empty environment

Effects

token is asked to associate sndr with its scope:

  • If the scope accepts the work, sndr is connected and started immediately, and spawn returns without waiting. The scope remembers the work until it completes.
  • If the scope does not accept the work (for example, it is closed), the sender is not started. Either spawn just returns, discarding the sender, or it throws; this is up to the scope. With counting_scope, work spawned after the scope has been joined is discarded and never runs.

The operation state of the started work is allocated dynamically, with the allocator from env if it has one, otherwise the allocator from the environment of the wrapped sender token.wrap(sndr) if that has one, otherwise with std::allocator<void>. It is destroyed, and the memory released, when the work completes, and only then is the work removed from the scope. If allocating or setting this up throws an exception, nothing is started, and the exception propagates out of spawn.

spawn(sndr, token) is ill-formed if sndr does not satisfy execution::sender, token does not satisfy execution::scope_token, or env is not a queryable object.

Customization point objects

The name execution::spawn denotes a customization point object, which is a const function object of a literal semiregular class type. The cv-unqualified version of its type is a tag type denoted as execution::spawn_t. See CustomizationPointObject for details.

What the sender may complete with

The result of the spawned work is dropped, since spawn returns void, so the sender may only complete in ways that need no handling:

  • It must complete with set_value(), that is, with no values, so that no result is silently discarded. To use spawn for a sender that produces a value, handle the value first, for example with then.
  • It must not complete with an error. An error that is not handled would have to either end the program or be ignored, and neither is acceptable by default, so the program has to handle every error explicitly before spawning, for example with upon_error or let_error, and the handling itself must not be able to fail. This is diagnosed at compile time. A function that can throw, passed to then, makes the sender able to fail, so it has to be noexcept, or its error has to be handled by a noexcept function.
  • It may complete with the stopped signal. Since the scope exists to keep track of when the work is finished, it does not matter whether the work finished by succeeding or by being cancelled, and cancellation is an explicit choice, so it needs no handling.

Notes

  • spawn covers what start_detached and ensure_started did in earlier drafts, which were removed because they started work with no way to know when it finished. The work started by spawn is attached to a scope, so the program can always find out when it is safe to destroy what the work uses.
  • The work starts eagerly, on the calling thread, as part of the call. This differs from most sender algorithms, which do nothing until the sender they return is started.
  • To get the result of the work, or to spawn a sender that has values or errors, use spawn_future, which returns a sender for the result.
  • spawn on its own does not wait for anything. Keep the scope alive, and join it, until the spawned work cannot use resources that are about to be destroyed.

Example

A scope tracks tasks spawned into it, here one per element of a vector. spawn returns immediately for each, and join waits for all of them before the results are used. The task is noexcept because spawn only accepts work that cannot fail.
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 <execution>
#include <print>
#include <vector>

namespace ex = std::execution;

int main()
{
    std::vector squares(5, 0);

    ex::counting_scope scope;

    for (int i = 0; i < 5; ++i)
        ex::spawn( ex::just()
                 | ex::then([&squares, i]() noexcept { squares[i] = i * i; })
                 , scope.get_token() );

    // Wait for every spawned task before reading the results.
    std::this_thread::sync_wait(scope.join());

    std::println("squares: {}", squares);
}

Output:

squares: [0, 1, 4, 9, 16]

See also

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]
tries to associate a sender with an asynchronous scope such that the scope can track the lifetime of any asynchronous operations created with the sender
(customization point object)[edit]