Namespaces
Variants

std::execution::stopped_as_optional

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

Turns cancellation into an ordinary result: the returned sender completes with a std::optional that holds the value of sndr if it succeeded, and is empty if sndr was cancelled (completed with the stopped signal). The returned sender never completes stopped itself.

A stopped completion is neither a result nor a failure, and by default it propagates upward and cancels everything that depends on it. In a coroutine it behaves like an exception that cannot be caught: it unwinds the chain of awaiting coroutines and bypasses catch (...). stopped_as_optional is the way to catch it: awaiting stopped_as_optional(sndr) lets the code that awaits decide what cancellation means, with an ordinary if on the optional.

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

Parameters

sndr - the sender to adapt; it must complete with exactly one set of values, and at least one value

Return value

A sender that completes with one value, an std::optional:

  • If sndr completes with values, the optional holds them. For a single value of type T, the result is std::optional<std::decay_t<T>>. If sndr sends several values, the optional holds a std::tuple of them: std::optional<std::tuple<A, B>>.
  • If sndr completes with the stopped signal, the optional is empty, and the returned sender completes with a value, not stopped.

Error completions of sndr are forwarded unchanged.

stopped_as_optional(sndr) is diagnosed at compile time if sndr can complete with more than one set of values, or if it never completes with values (so that there is nothing to put into the optional).

Customization point objects

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

Details

  • Nothing runs when the sender is built. The input is started, and its completion converted, only when the returned sender is started.
  • The values are copied or moved into the optional (move-only values are fine).
  • stopped_as_optional never changes where anything runs: the returned sender completes on the execution agent on which sndr completed.
  • It is equivalent to wrapping the values in an optional with then, and replacing the stopped completion with an empty optional using let_stopped and just; the adaptor saves writing that by hand.

Notes

  • To handle cancellation by running another asynchronous operation, use let_stopped; to turn it into a plain value of your choice, use upon_stopped; to turn it into an error, use stopped_as_error. stopped_as_optional is the one to choose when "cancelled" should be told apart from every real value without picking a sentinel.
  • The empty optional carries no data: it says that the operation was cancelled, not why. If several different things can be cancelled and you need to tell them apart, use let_stopped or stopped_as_error on each.
  • Handling a stopped completion this way is often done in coroutines: because the stopped signal unwinds the coroutine chain as an uncatchable exception, a coroutine that wants to react to cancellation (clean up, return a default, end a loop) has to co_await the sender through stopped_as_optional first. The same applies to loops over a sequence of senders that arrive asynchronously, such as user actions or sensor readings: awaiting each element through stopped_as_optional lets the loop end cleanly when an element is cancelled.

Example

A job is scheduled on an event loop while stop has already been requested through the environment's stop token, so it is cancelled before it starts. Without stopped_as_optional, the whole operation would end up cancelled, and sync_wait would return an empty result. With it, cancellation arrives as an empty optional that the program can inspect.
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 <optional>
#include <print>
#include <stop_token>
#include <thread>

namespace ex = std::execution;

// A job that returns a number, run on an event loop. It is cancelled if
// stop has been requested through the stop token of the given source.
std::optional<int> run_job(std::inplace_stop_source& stop_source)
{
    ex::run_loop loop;
    std::jthread worker([&] { loop.run(); });

    auto job = ex::schedule(loop.get_scheduler())
             | ex::then([] { return 42; });

    auto sndr = ex::write_env(std::move(job),
                              ex::prop{std::get_stop_token, stop_source.get_token()})
              | ex::stopped_as_optional();

    auto [result] = std::this_thread::sync_wait(std::move(sndr)).value();
    loop.finish();
    return result;
}

int main()
{
    std::inplace_stop_source not_stopped;
    std::inplace_stop_source stopped;
    stopped.request_stop();

    if (auto result = run_job(not_stopped))
        std::println("job finished: {}", *result);
    else
        std::println("job was cancelled");

    if (auto result = run_job(stopped))
        std::println("job finished: {}", *result);
    else
        std::println("job was cancelled");
}

Output:

job finished: 42
job was cancelled

See also

returns a sender that maps the stopped channel to an error
(customization point object)[edit]
chains a function onto a sender, calling it if the sender is cancelled and sending its result on as a value
(customization point object)[edit]
chains a function onto a sender, calling it if the sender is cancelled and continuing with the sender it returns
(customization point object)[edit]