Execution control (C++)

The execution control library, also sometimes called senders/receivers framework, is a part of the C++ Standard Library which provides a composable framework for asynchronous execution, introduced in C++26. Rather than threading, the library uses execution as a first-class concept, promising separation of what code does from where and how it runs, in a uniform API for coordinating asynchronous work on various backends.

Its contents are provided in the <execution> header, under the namespace std::execution.

Just like std::ranges, std::execution is lazily evaluated and uses operator| as a pipe operator to chain operations, similar to a fluent API.

History

C++, before the introduction of the execution control library, had no asynchronous programming framework. Third party libraries offered alternative asynchronous frameworks, such as Christopher Kohlhoff's Asio (which later was integrated into Boost as boost::asio), which offered callbacks and execution contexts for asynchronous I/O; this later became the reference implementation for the Networking TS.

C++11 introduced std::promise<T> and std::future<T> which offered a futures and promises model, while std::async() was used to run a function asynchronously (potentially in a separate thread) and return a std::future object, specifically taking a function of type F and returning a future<invoke_result_t<decay_t<F>, decay_t<Args>...>>, as well as allowing specifying a std::launch policy. However, these libraries lacked true non-blocking asynchrony, and lacked the true language support seen in other languages such as C# and Rust, which featured true async/await systems. In addition, std::future was not composable.

#include <future>
#include <numeric>
#include <utility>
#include <vector>

using std::future;
using std::launch;
using std::vector;

// a heavy, CPU-bound operation
vector<double> applyFilter(vector<double> image) noexcept {
    for (double& pixel : image) {
        pixel *= 2.0; // Example heavy work
    }
    return image;
}

// Runs on the calling thread while applyFilter runs on the spawned thread
void performOtherWork() {
    // ...
}

// Start the work on an OS thread
vector<double> processImage(vector<double> image) {
    // Eagerly spawn a new OS thread
    future<vector<double>> fut = std::async(launch::async, applyFilter, std::move(image));

     // Other work on the thread, while processImage runs concurrently
     performOtherWork();

     // Block the thread until processImage completes, waiting here
     return fut.get();
}

int main(int argc, char* argv[]) {
    // a large amount of data
    vector<double> imagePixels(5'000'000);
    std::iota(imagePixels.begin(), imagePixels.end(), 1.0);

    vector<double> processedImage = processImage(std::move(imagePixels));
}

Despite this, some attempts to modernise the futures/promises library were made, including composability (future::then() for sequential chaining, and when_all()/when_any() for coordinating multiple concurrent operations), in the Concurrency TS. This TS was never merged.

Additional concurrency items were std::thread introduced in C++11, which represents an operating system thread. std::jthread, introduced in C++20, had the additional behavior of automatically rejoining on destruction. It paired with std::stop_token, a cancellation token for a view over whether a stop request has been made for cooperative thread cancellation.

C++20 introduced coroutines to the language, supporting functions which can suspend execution and resume later. However, no async keyword was added; instead, a function is coloured by return type, and any function which uses keywords prefixed by co_ is such a coroutine:

However, this did not introduce any library support for coroutines, other than just std::coroutine_handle<Prom> (a non-owning pointer-like object used to resume or destroy a suspended coroutine). C++23 introduced a generator class for synchronous and lazy-evaluated ranges, std::generator<Ref, V, Alloc>.

import std;

using std::generator;

generator<int> range(int n) noexcept {
    for (int i = 0; i < n; ++i) {
        co_yield i;
    }
}

int main() {
    for (int i : range(10)) {
        std::println("{}", i);
    }
    return 0;
}

Although the std::execution namespace was first introduced in C++17, it was inhabited by parts of the algorithms library, storing execution policy types.

A proposal for a "unified executors" library was made in 2020, based on Meta's libunifex library. The Networking TS, with its asynchronous I/O model, was abandoned in favour of executors. This was later refined in 2024 by NVIDIA's stdexec library, which eventually became the reference implementation for std::execution, which was accepted into the standard for C++26 that same year. Inside this proposal were additional cancellation tokens (also known as stop tokens) inside the <stop_token> header, which are general-purpose utilities (a thread-safe way to check if a stop request has been made or is possible) but were primarily motivated by std::execution's development.

Execution policies

In C++17, the execution policies (originally from the Parallelism Technical Specification) were standardised. std::is_execution_policy<T> checks if a class represents an execution policy. The execution policies are (with the tag objects):

Architecture

The library itself consists of:

Core operations

  • std::execution::connect(snd, rcv) connects the sender snd to the receiver rcv, and returns its operation state.
  • std::execution::start(op) starts the asynchronous operation with the operation state object op (created by connecting a sender to a receiver with std::execution::connect()).
  • std::execution::set_value(rcv, vals...) is called by a sender to indicate to the receiver rcv that its connected operation has succeeded, passing the results vals....
  • std::execution::set_error(rcv, err) is called by a sender to indicate to the receiver rcv that its connected operation has failed, passing the error err.
  • std::execution::set_stopped(rcv) is called by a sender to indicate to the receiver rcv that its connected operation stopped (ending early without a result), representing neither a success nor a failure.

Senders

std::execution::sender<Snd> is a concept that specifies that a type is a sender. A sender must declare a nested type alias named sender_concept, that resolves to std::execution::sender_tag (or any type that derives from it).

using sender_concept = std::execution::sender_tag;

std::execution::sender_in<Snd, Envs...> is a concept that specifies that the ways a sender can complete are known for a sender Snd and environments Envs....

std::execution::dependent_sender<Snd> specifies that the ways a sender can complete depend on the environment it is started in.

Non-coroutine senders are just chained with factories and adaptors as descriptions of work, allowing their size to be known at compile-time without any need for heap allocations.

Task

std::execution::task<T, Env>, the standard C++ coroutine task type, is a sender which can be used as the return type of a coroutine; the template parameters T (the type that the value in set_value() is completed with) and Env (the environment that customises the task, deciding its allocator, start scheduler, stop source, error types and environment type) are respectively by default void and std::execution::env<>. std::execution::env<Envs...> is an environment that combines any number of queryable objects into a single queryable object.

import std;

using std::string_view;
using std::execution::task;

task<int> fetchUserId(string_view username) {
    // In a real example, co_await an async database or network call
    co_return 100;
}

task<void> greetUser(string_view username) {
    int id = co_await fetchUserId(username);
    std::println("Welcome back, user #{}", id);
}

std::execution::task<T, Env> is lazy; it will never run until it is explicitly co_awaited. If it is destroyed before ever being co_awaited, it will have never ran. During destruction, the task's destructor runs destroy() on its internal std::coroutine_handle.

std::execution::with_error<E> is a type that holds an error that a std::execution::task coroutine passes to co_yield to complete with that error, without throwing an exception.

std::execution::task_scheduler is a type-erased scheduler, to hold and represent the "current" scheduler inside a std::execution::task coroutine.

Because std::execution::task was not added until C++26, while coroutines were first added in C++20, several third-party libraries had created their own coroutine task types. These include cppcoro, libunifex, taskflow, and stdexec (whose task type was eventually the chosen model).

Factories

A sender factory is an algorithm that takes no senders, and returns a sender. These are used to begin a chain of work.

  • std::execution::just(args...) completes immediately by passing args... to the receiver's set_value channel.
  • std::execution::just_error(err) completes immediately by passing err to the receiver's set_error channel.
  • std::execution::just_stopped() completes immediately with cancellation via the set_stopped() channel.
  • std::execution::schedule(sch) completes on schedule sch's execution context.
  • std::execution::read_env(query) queries the receiver's environment and passes the result as a value.

Adaptors

An adaptor is an algorithm that takes one or more existing senders and returns a new, composed sender representing the next step in the pipeline. These use the piping operator, operator|.

  • std::execution::then chains a function to a sender by calling it with the sender's values and then sending its result.
  • std::execution::on runs a sender on the provided scheduler.
  • std::execution::bulk runs a function for every index in a range (spreading the work over a scheduler's execution resources).
  • std::execution::when_all adapts multiple input senders into a sender that completes once all the inputted senders have completed.

Consumers

Sender consumers are algorithms that take at least one sender, but do not return any sender.

The following "spawn" functions are designed to replace unsafe fire-and-forget patterns with structured concurrency. Both eagerly launch the given sender snd and its associated scope token token, and take env, a queryable object, as an optional parameter joined into the environment the work sees.

  • std::execution::spawn(snd, token, env) returns nothing immediately (void) without waiting for the result.
  • std::execution::spawn_future(snd, token, env) returns a sender immediately, without waiting for the result. This is used to attach work to it without the background task having finished.

The following "sync_wait" functions block the current thread until the sender snd completes and returns its result. In other words, the "sync_wait" functions are used to co_await a coroutine from inside a non-coroutine.

  • std::this_thread::sync_wait(snd) returns optional<tuple<Ts...>>.
  • std::this_thread::sync_wait_with_variant(snd) returns optional<variant<Ts...>>.

If the awaited sender completes successfully with zero values (i.e. void, for example a task<void>), then the returned tuple/variant will be empty.

import std;

using std::exception;
using std::exception_ptr;
using std::optional;
using std::string;
using std::string_view;
using std::tuple;
using std::vector;
using std::execution::counting_scope;
using std::execution::parallel_scheduler;
using std::execution::scheduler;
using std::execution::sender;
using std::execution::starts_on;
using std::execution::task;
using std::execution::upon_error;

task<void> sendWelcomeEmail(string_view email, string_view smtpHost) {
    // Await the network client here...
    co_return;
}

task<vector<string>> getEmails() {
    // Implementation for some coroutine that fetches the list of emails...
}

task<void> handleSignups(scheduler auto sch, string_view smtpHost) {
    counting_scope scope;
    vector<string> emails = co_await getEmails();
    for (const string& email : emails) {
        sender auto job = starts_on(sch, sendWelcomeEmail(email, smtpHost))
            | upon_error([email](exception_ptr p) noexcept -> void {
                try {
                    std::rethrow_exception(p);
                } catch (const exception& e) {
                    std::println("Failed to email {}: {}", email, e.what());
                }
            });

        std::execution::spawn(std::move(job), scope.get_token());
        std::println("Account created for {}, response sent to user", email);
    }
    co_await scope.join();
}

int main(int argc, char* argv[]) {
    parallel_scheduler pool = std::execution::get_parallel_scheduler();
    static constexpr string_view MAIL_SERVICE_URL = "smtp://example.com";
    
    try {
        optional<tuple<>> result = std::this_thread::sync_wait(handleSignups(pool, MAIL_SERVICE_URL));
        if (result.has_value()) {
            std::println("All signups and background emails finished!");
        } else {
            std::println(std::cerr, "Signup batch was cancelled.");
        }
    } catch (const exception& e) {
        std::println(std::cerr, "Signup batch aborted: {}", e.what());
    }
}

Receivers

A receiver is a callback that consumes a result produced by a sender. It has three "channels" through which a sender may propagate its results:

  • value, representing success; tied to std::execution::set_value()
  • error, representing failure; tied to std::execution::set_error()
  • stopped, representing cancelled; tied to std::execution::set_stopped()

A receiver must declare a nested type alias named receiver_concept, that resolves to std::execution::receiver_tag (or any type that derives from it).

using receiver_concept = std::execution::receiver_tag;

Receivers provide an extensible execution environment, which is a queryable object (i.e. a collection of key/value pairs where each key is a "query object", a customisation point object).

  • std::execution::receiver<Rcv> specifies that a type Rcv is a receiver.
  • std::execution::inlinable_receiver<Rcv, Op> specifies that a receiver Rcv can be recreated from a pointer to the operation state Op created when the receiver was connected to a sender.

Schedulers

std::execution::scheduler<Sch> is a concept that specifies a type to be a scheduler. A scheduler is an execution resource, and is a factory for a sender that completes its receiver. A scheduler must declare a nested type alias named scheduler_concept, that resolves to std::execution::scheduler_tag (or any type that derives from it).

using scheduler_concept = std::execution::scheduler_tag;

std::execution::parallel_scheduler is a scheduler class for a shared execution resource that runs work in parallel; it can only be created using std::execution::get_parallel_scheduler().

The original C++26 proposal lacks time-based schedulers (though these do exist in stdexec as exec::timed_scheduler). The proposal paper suggests future papers propose additional schedulers such as timed schedulers, asynchronous I/O and networking. stdexec currently only has one native asynchronous I/O backend, io_uring (for Linux).

Parallel scheduler replacement

The std::execution::parallel_scheduler_replacement library contains an API for allowing the replacement or customization of the default backend implementation of the system parallel scheduler. Within it are the following items:

  • query_parallel_scheduler_backend() is a function that returns a shared_ptr<parallel_scheduler_backend> for the active parallel scheduler instance, which can be replaced at link time.
  • parallel_scheduler_backend is an interface with three methods for backends to implement:
    • void schedule(receiver_proxy& rp, span<byte> s) noexcept;, called by the parallel_scheduler for the sender returned by schedule().
    • void schedule_bulk_chunked(size_t n, bulk_item_receiver_proxy& rp, span<byte> s) noexcept;, called by the parallel_scheduler for bulk_chunked, dividing the range [0,n) into subranges and calls rp.execute(begin, end) for each subrange [𝚋𝚎𝚐𝚒𝚗,𝚎𝚗𝚍).
    • void schedule_bulk_unchunked(size_t n, bulk_item_receiver_proxy& rp, span<byte> s) noexcept;, called by parallel_scheduler for bulk_unchunked, doing the same as schedule_bulk_chunked() except that all calls to execute() are rp.execute(i, i + 1) for an index i∈[0,n).
  • receiver_proxy is a proxy interface for use by the custom backend to pass values, errors, or loop iteration notifications back to the sender/receiver pipeline.
    • void set_value() noexcept; completes the operation by calling std::execution::set_value() on the receiver.
    • void set_error(exception_ptr e) noexcept; completes the operation with an error by calling std::execution::set_error() on the receiver.
    • void set_stopped() noexcept; completes the operation without running the work by calling std::execution::set_stopped(). on the receiver.
  • bulk_item_receiver_proxy is another interface that extends receiver_proxy, with an additional method execute().
    • void execute(size_t begin, size_t end) noexcept; runs the iterations in the range [𝚋𝚎𝚐𝚒𝚗,𝚎𝚗𝚍) of the bulk algorithm.

This is a minimal example of those interfaces above in use.

import std;

using std::byte;
using std::exception;
using std::exception_ptr;
using std::inplace_stop_token;
using std::optional;
using std::span;
using std::string_view;
using std::vector;
using std::execution::get_stop_token;
using std::execution::receiver_tag;
using std::execution::parallel_scheduler_replacement::bulk_item_receiver_proxy;
using std::execution::parallel_scheduler_replacement::parallel_scheduler_backend;
using std::execution::parallel_scheduler_replacement::receiver_proxy;

/**
 * @class SimpleChunkingBackend
 * @brief A backend for a threadless platform, which runs all work at once
 * on the thread that starts it, dividing bulk work into chunks of up to 4
 *
 * @implements parallel_scheduler_backend
 */
class SimpleChunkingBackend final : public parallel_scheduler_backend {
private:
    vector<receiver_proxy*> pending;
public:
    void schedule(receiver_proxy& rp, span<byte> _) noexcept override {
        try {
            pending.push_back(&rp);
        } catch (const exception& e) {
            rp.set_error(std::make_exception_ptr(e));
        }
    }

    void schedule_bulk_chunked(size_t n, bulk_item_receiver_proxy& rp, span<byte> _) noexcept override {
        for (size_t i = 0; i < n; i += 4) {
            rp.execute(i, std::min(i + 4, n));
        }
        rp.set_value();
    }

    void schedule_bulk_unchunked(size_t n, bulk_item_receiver_proxy& rp, span<byte> _) noexcept override {
        for (size_t i = 0; i < n; ++i) {
            rp.execute(i, i + 1);
        }
        rp.set_value();
    }

    void run_pending() {
        for (receiver_proxy* rp : std::exchange(pending, {})) {
            optional<inplace_stop_token> st = rp->try_query<inplace_stop_token>(get_stop_token);
            if (st.has_value() && st->stop_requested()) {
                rp->set_stopped();
            } else {
                rp->set_value();
            }
        }
    }
};

/**
 * @class SimpleBulkProxy
 * @brief A type-erased receiver proxy for bulk callables and downstream
 * receivers for use with parallel_scheduler_backend
 *
 * @tparam BulkFn A callable of signature (size_t, size_t) -> void
 * @tparam DownstreamRcvr A receiver type that receives notifications
 * @implements bulk_item_receiver_proxy
 */
template <typename BulkFn, typename DownstreamRcvr>
class SimpleBulkProxy final : public bulk_item_receiver_proxy {
private:
    BulkFn fn;
    DownstreamRcvr rcv;
public:
    SimpleBulkProxy(BulkFn f, DownstreamRcvr r):
        fn{std::move(f)}, rcv{std::move(r)} {}

    void set_value() noexcept override {
        std::move(rcv).set_value();
    }

    void set_error(exception_ptr e) noexcept override {
        std::move(rcv).set_error(std::move(e));
    }

    void set_stopped() noexcept override {
        std::move(rcv).set_stopped();
    }

    void execute(size_t begin, size_t end) noexcept override {
        try {
            fn(begin, end);
        } catch (const exception& e) {
            std::println(std::cerr, "A fatal error was caught at [{}, {}): {}", begin, end, e.what());
            std::terminate(); // Terminate upon a caught exception.
        } catch (...) {
            std::println(std::cerr, "An unknown fatal error was caught at [{}, {})", begin, end);
            std::terminate();
        }
    }
};

/**
 * @struct SimpleReceiver
 * @brief A minimal receiver for demonstration
 */
struct SimpleReceiver {
    using receiver_concept = receiver_tag; // A necessary tag to to mark a receiver

    void set_value() && noexcept {
        std::println("Bulk operation completed!");
    }

    void set_error(exception_ptr _) && noexcept {
        std::println("Bulk operation failed!");
    }

    void set_stopped() && noexcept {
        std::println("Bulk operation halted abruptly!");
    }
};

int main(int argc, char* argv[]) {
    vector<int> squares(10);

    SimpleBulkProxy proxy(
        [&squares](size_t begin, size_t end) -> void {
            for (size_t i = begin; i < end; ++i) {
                squares[i] = static_cast<int>(i * i);
            }
        },
        SimpleReceiver()
    );

    SimpleChunkingBackend backend;
    backend.schedule_bulk_chunked(data.size(), proxy, {});

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

Operation states

An operation state is an object that contains the state needed by the asynchronous operation. An operation state must declare a nested type alias named operation_state_concept, that resolves to std::execution::operation_state_tag (or any type that derives from it).

using operation_state_concept = std::execution::operation_state_tag;

It is represented by the concept std::execution::operation_state<Op>, specifying that Op is an operation state.

std::execution::connect(snd, rcv) (for sender snd and receiver rcv) constructs the operation state in place; the returned operation state op is passed to std::execution::start(op) to begin the asynchronous work.

Execution scopes

An execution scope is a structured concurrency primitive that manages the lifetime of dynamically spawned asynchronous work, tracking background tasks and guaranteeing that they finish before the scope itself is safely destroyed.

  • std::execution::scope_association<Assoc> specifies that Assoc represents an active association with an asynchronous scope.
  • std::execution::scope_association<Tok> specifies that Tok is a non-owning handle (token) to an asynchronous scope, behaving like a reference to an asynchronous scope.

Applications

The earlier example using C++11's std::future, could instead be done using std::execution in the following:

import std;

using std::vector;
using std::execution::continues_on;
using std::execution::just;
using std::execution::parallel_scheduler;
using std::execution::sender;
using std::execution::task;
using std::execution::then;
using std::execution::when_all;

// A heavy, CPU-bound operation
vector<double> applyFilter(vector<double> image) noexcept {
    for (double& pixel : image) {
        pixel *= 2.0; // Example heavy work
    }
    return image;
}

// Runs concurrently while applyFilter runs on the thread pool
void performOtherWork() {
    // ...
}

// Perform operations concurrently
task<vector<double>> processImage(vector<double> image) {
    parallel_scheduler pool = std::execution::get_parallel_scheduler();

    // Package both units of work as lazy senders targeting the thread pool
    sender auto filterWork = just(std::move(image))
        | continues_on(pool)
        | then(applyFilter);
    sender auto otherWork = just()
        | continues_on(pool)
        | then(performOtherWork);

    // Run both concurrently and suspend until both complete
    auto [filteredImage] = co_await when_all(
        std::move(filterWork),
        std::move(otherWork)
    );

    co_return filteredImage;
}

int main(int argc, char* argv[]) {
    // A large amount of data
    vector<double> imagePixels(5'000'000);
    std::ranges::iota(imagePixels, 1.0);

    // Block at the top-level entry point only
    auto [processedImage] = std::this_thread::sync_wait(
        processImage(std::move(imagePixels))
    ).value();
}

The library is particularly of interest in high-performance computing (HPC) and heterogeneous computing environments. Because the sender/receiver model decouples task description from execution context, it can be used to express asynchronous pipelines that target multi-core CPUs and GPUs through a unified interface. In addition, it has been used for scientific computing, GPU acceleration, and in particular parallelising iterative algorithms and physical simulations.

The library has further been used in parallel runtime systems for support for dynamic parallel runtimes, allowing interfacing with distributed and task-based execution.

See also