Namespaces
Variants

std::execution::affine

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 affine_t { /* unspecified */ };
(1) (since C++26)
inline constexpr affine_t affine{};
(2) (since C++26)
(customization point object)
Call signature
execution::sender auto affine( execution::sender auto sndr );
(3) (since C++26)

Adapts a sender so that it completes on the scheduler the surrounding operation was started on, no matter where the adapted sender itself ends up running. That scheduler is obtained from the receiver's environment with execution::get_start_scheduler.

This is how execution::task keeps its scheduler affinity: a coroutine that co_awaits a sender resumes on the scheduler it was running on before the co_await, even if the awaited work finished on some other thread.

affine is a pipeable sender adaptor: sndr | affine() is equivalent to affine(sndr).

If the adapted sender is known to complete on the right scheduler already, the extra scheduling step is skipped.

Parameters

sndr - the sender to adapt; it may run, and complete, on any execution agent

Return value

A sender that starts sndr on the current execution agent, and delivers its completion (value, error, or stopped) on an execution agent of the scheduler the operation was started on. If the current execution agent already belongs to that scheduler's execution resource, the completion may be delivered immediately, before start returns.

affine(sndr) is ill-formed if sndr does not satisfy execution::sender.

Requirements on the start scheduler

The start scheduler must be infallible: scheduling work onto it must not be able to fail, because there would be no correct scheduler left to report the failure on. Concretely, the sender returned by schedule(sch) may complete only with set_value(), plus set_stopped() if the receiver's stop token can request stop.

When the receiver's environment does not provide get_start_scheduler, or provides a scheduler that is not infallible, the adapted sender cannot be used with that receiver. This is diagnosed at compile time, not at run time.

Among the standard schedulers, inline_scheduler, task_scheduler, and the scheduler of run_loop are infallible. parallel_scheduler is not: it may complete with an error. To use it with affine (or with a task that is started on it), wrap it in a scheduler that decides what a scheduling failure means. The standard library does not provide such an adaptor, but there are two reasonable choices for what the wrapper does when scheduling onto the underlying scheduler fails:

  • Terminate the program.
  • Complete anyway, on an execution agent where the wrapper can schedule infallibly (for example the one the work completed on). The program keeps running, but affinity is lost in the failure case, and nothing reports that the work did not resume on the intended scheduler.

Customization

By default, affine completes the adapted sender and then reschedules onto the start scheduler. The scheduling operation is run with a stop token that never requests stop, so the completion is delivered on the right scheduler even when the adapted sender completes with set_stopped().

A sender can opt out of the rescheduling when it knows that it always completes where it was started (for example just): if sndr.affine() is well-formed, its result is used instead of the default behavior.

It is unspecified whether the senders of the standard library provide such a member function. It is recommended that implementations provide one for just, just_error, just_stopped, read_env, and write_env.

Customization point objects

The name execution::affine 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::affine_t. See CustomizationPointObject for details.

Notes

  • Unlike continues_on, which moves the completion to a scheduler that you pass in, affine always goes back to where the operation started. It also requires an infallible scheduler and does not forward the receiver's stop state to the scheduling operation. Both restrictions exist for the same reason: the final scheduling step is the one that puts the completion back on the right execution agent, so if it could fail or be stopped, there would be no correct agent left to report that on, and the guarantee would silently not hold. Making the requirement a compile-time check means a program cannot end up in that situation at run time.
  • There is no scheduler argument because the start scheduler is usually not known when a sender is built: it is determined by the receiver the sender is eventually connected to (for a task, the scheduler it is started on). affine therefore asks the receiver's environment, with get_start_scheduler, when it is connected.
  • The algorithm was originally specified as affine_on(sndr, sch), taking the scheduler as a second argument.

Example

work runs on a worker thread. Without affine, whatever follows it also runs on the worker thread; with affine, it runs on the thread that called sync_wait, which is the scheduler the operation was started on.
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 <iostream>
#include <thread>

namespace ex = std::execution;

int main()
{
    const auto main_id = std::this_thread::get_id();

    ex::run_loop worker_loop;
    std::jthread worker([&] { worker_loop.run(); });

    // Completes on the worker thread.
    auto work = ex::schedule(worker_loop.get_scheduler());

    auto without_affine = work
                        | ex::then([&] { return std::this_thread::get_id() == main_id; });

    auto with_affine = ex::affine(work)
                     | ex::then([&] { return std::this_thread::get_id() == main_id; });

    auto [a] = std::this_thread::sync_wait(std::move(without_affine)).value();
    auto [b] = std::this_thread::sync_wait(std::move(with_affine)).value();

    std::cout << std::boolalpha
              << "continued on the calling thread without affine: " << a << '\n'
              << "continued on the calling thread with affine:    " << b << '\n';

    worker_loop.finish();
}

Output:

continued on the calling thread without affine: false
continued on the calling thread with affine:    true

See also

adapts a provided sender into one that completes on the provided scheduler's execution resource
(customization point object)[edit]
asks a queryable object for the scheduler an operation will be or was started on
(customization point object)[edit]