# Senders and receivers (std::execution)

> C++26's std::execution describes asynchronous work as lazy sender values that complete on exactly one of three channels: value, error, or stopped. Algorithms compose senders, schedulers say where work runs, and nothing happens until a sender is connected to a receiver and started.

- **Source:** C++ Atlas (https://cppatlas.com/topics/senders-and-receivers)
- **Track:** C++26
- **Estimated reading time:** 16 minutes
- **ISO C++ clauses:** [exec.async.ops] (https://eel.is/c++draft/exec.async.ops), [exec.recv] (https://eel.is/c++draft/exec.recv), [exec.opstate] (https://eel.is/c++draft/exec.opstate), [exec.snd] (https://eel.is/c++draft/exec.snd), [exec.sched] (https://eel.is/c++draft/exec.sched), [exec.getcomplsigs] (https://eel.is/c++draft/exec.getcomplsigs), [exec.then] (https://eel.is/c++draft/exec.then), [exec.let] (https://eel.is/c++draft/exec.let), [exec.when.all] (https://eel.is/c++draft/exec.when.all), [exec.starts.on] (https://eel.is/c++draft/exec.starts.on), [exec.continues.on] (https://eel.is/c++draft/exec.continues.on), [exec.on] (https://eel.is/c++draft/exec.on), [exec.sync.wait] (https://eel.is/c++draft/exec.sync.wait), [exec.counting.scopes] (https://eel.is/c++draft/exec.counting.scopes), [exec.task] (https://eel.is/c++draft/exec.task)
- **cppreference links:** [Execution control library](https://en.cppreference.com/w/cpp/execution), [std::execution::then](https://en.cppreference.com/w/cpp/execution/then), [std::execution::let_value](https://en.cppreference.com/w/cpp/execution/let_value), [std::execution::when_all](https://en.cppreference.com/w/cpp/execution/when_all), [std::execution::on](https://en.cppreference.com/w/cpp/execution/on), [std::stop_token](https://en.cppreference.com/w/cpp/thread/stop_token)
- **Prerequisites:** futures-promises-and-async, threads-and-jthread, coroutines, concepts-and-constraints, customization-points-and-niebloids

## The one idea

A **sender** is a value that describes some asynchronous work but does not do it. You build bigger senders out of smaller ones with algorithms such as `then` and `when_all`, and the result is still just a description. Work starts only when a sender is **connected** to a **receiver**, which is the continuation that wants the result, and the resulting **operation state** is **started**. When the work finishes, it calls exactly one of three functions on the receiver: `set_value` with the results, `set_error` with one error, or `set_stopped` with nothing, meaning the work was cancelled.

That design replaces `std::future` for composable asynchrony. A future is eager: the work is already running, so the future needs a shared heap-allocated state and synchronization to hand the result over. A sender is lazy, so the whole pipeline can be assembled first, and the operation state can live in one object, often on the stack, with no allocation and no locks on the happy path.

This is C++26. The core is P2300R10, adopted in June 2024. C++26 also adds P3149R11 (async scopes, `spawn`, and `counting_scope`), P3552R3 (the `std::execution::task` coroutine type), P2079R10 (`parallel_scheduler`), P3175R3 (the reworked `on`), P3284R4 (`write_env` and `unstoppable`), P3481R5 (the three `bulk` variants), and P3557R3 (sender diagnostics computed with `constexpr` exceptions). P3187R1 removed `ensure_started` and `start_detached` from the design before it was adopted, and `split` is not in the final text either. Everything here follows N5050, the final C++26 draft sent to the international ballot. That ballot closed in October 2026 and was reported as not approved, so check the status before you quote this as published ISO C++.

No shipping standard library implements `<execution>`'s sender part yet. GCC 16's libstdc++ does not define `__cpp_lib_senders`, and Clang 21's libc++ does not either. The examples below are written against the N5050 names, and each was compiled and run with GCC 16 against NVIDIA's stdexec reference implementation by mapping `std::execution` to `stdexec`.

> **Mental model.** A sender is a recipe, a receiver is the plate it lands on, and `connect` plus `start` is cooking. The recipe can be copied, combined, and passed around, and no food exists until somebody starts the operation.

## The asynchronous operation contract

[exec.async.ops] states the rules that every sender, receiver, and algorithm relies on.

- An operation is started at most once, and once started it completes **exactly once**.
- It completes with one of three completion operations: a value completion with any number of arguments, an error completion with exactly one argument, or a stopped completion with none.
- The operation state must stay alive, at the same address, until the operation completes. Destroying it earlier is undefined behaviour, and library operation states cannot be copied or moved at all.
- A child operation completes before its parent does. That makes `std::execution` a **structured** concurrency model, in which lifetimes nest like function calls.

A sender advertises what it may complete with through its **completion signatures**, a type such as `completion_signatures<set_value_t(int), set_error_t(std::error_code), set_stopped_t()>`. Algorithms compute their own completion signatures from those of their children at compile time. That is how `when_all` knows what to pass on, and how `sync_wait` knows its return type. In C++26, a sender computes these with a `static consteval` member function template, and an invalid combination throws an exception during constant evaluation. That is how P3557 makes the diagnostics readable.

```text
  sender ──connect(receiver)──► operation state ──start()──► work runs
                                                               │
                         exactly one of: set_value(rcvr, vs...)
                                         set_error(rcvr, e)
                                         set_stopped(rcvr)
```

> **Standardese.** [exec.opstate.general] says that if an `operation_state` object is destroyed during the lifetime of its asynchronous operation, the behaviour is undefined. It also makes a program ill-formed if it copies or moves an operation state created by connecting a library-provided sender.

## Composing with algorithms

Sender factories start a chain: `just(vs...)` completes with values, `just_error(e)` with an error, `just_stopped()` with a stop, and `schedule(sch)` completes on a scheduler's execution resource. Sender adaptors take a sender and return a new one, and each has a pipeable form, so `s | then(f)` means `then(s, f)`.

- `then(f)` calls `f` with the values and sends its result as a value. `upon_error(f)` and `upon_stopped(f)` do the same for the other two channels, turning them back into values.
- `let_value(f)` calls `f` with the values, and `f` returns a *sender*. That sender is connected and started, and its completion becomes the completion of the whole thing. This is the monadic bind, and it is how you write "then do this asynchronous thing next". `let_error` and `let_stopped` exist too.
- `when_all(s1, s2, ...)` starts all of its children and completes with all of their values concatenated. If any child fails or is stopped, it asks the others to stop and forwards the first error or the stop.
- `into_variant`, `stopped_as_optional`, and `stopped_as_error` reshape completions. `bulk`, `bulk_chunked`, and `bulk_unchunked` run a function over an index range.

A sender consumer finally runs the chain. `std::this_thread::sync_wait(s)` connects `s` to its own receiver, starts it, and blocks the calling thread until it completes.

```cpp
#include <execution>
#include <cstdio>

namespace ex = std::execution;

int main() {
  bool ran = false;
  ex::sender auto work =
      ex::when_all(ex::just(1), ex::just(2.5))
    | ex::then([&](int i, double d) { ran = true; return i + d; })
    | ex::let_value([](double sum) { return ex::just(sum * 2); });

  std::printf("%d\n", ran);                         // prints 0: nothing has run yet
  auto [result] = std::this_thread::sync_wait(std::move(work)).value();
  std::printf("%d %.1f\n", ran, result);            // prints 1 7.0
}
```

`sync_wait` returns `std::optional<std::tuple<Values...>>`. A value completion produces an engaged optional, and a stopped completion produces an empty one. An error is thrown: an `exception_ptr` is rethrown as is, an `error_code` is thrown as `std::system_error`, and any other error type is thrown as itself. `sync_wait` requires the sender to have **exactly one** value completion signature, because otherwise it could not name a single tuple type. `sync_wait(just_stopped())` is therefore ill-formed, and so is a sender that might send either an `int` or a `string`. `sync_wait_with_variant` handles that case.

> **Pitfall.** `then` with a callable that returns a sender does not run that sender. It sends the sender object as a value, so the result type of `sync_wait(just() | then([] { return just(42); }))` holds a sender, not an `int`. Use `let_value` whenever the callable returns more work.

## A sender by hand

Writing a sender shows how little machinery there is. This one completes on a different channel depending on its input.

```cpp
#include <execution>
#include <cstdio>
#include <system_error>
#include <utility>

namespace ex = std::execution;

struct parse_sender {
  using sender_concept = ex::sender_tag;
  int input;

  template <class Self, class... Env>
  static consteval auto get_completion_signatures() {
    return ex::completion_signatures<ex::set_value_t(int),
                                     ex::set_error_t(std::error_code),
                                     ex::set_stopped_t()>{};
  }

  template <class Rcvr>
  struct op {
    using operation_state_concept = ex::operation_state_tag;
    Rcvr rcvr;
    int input;
    void start() & noexcept {
      if (input > 0)       ex::set_value(std::move(rcvr), input * 2);
      else if (input == 0) ex::set_stopped(std::move(rcvr));
      else ex::set_error(std::move(rcvr), std::make_error_code(std::errc::invalid_argument));
    }
  };

  template <class Rcvr>
  op<Rcvr> connect(Rcvr rcvr) && { return {std::move(rcvr), input}; }
};

int main() {
  auto r1 = std::this_thread::sync_wait(parse_sender{21});   // optional<tuple<int>> holding 42
  auto r2 = std::this_thread::sync_wait(parse_sender{0});    // empty optional: stopped
  std::printf("%d %d\n", std::get<0>(*r1), r2.has_value());  // prints 42 0
  try {
    std::this_thread::sync_wait(parse_sender{-1});
  } catch (const std::system_error&) {                       // the error_code arrives as system_error
    std::puts("invalid argument");
  }
}
```

The completion functions are `noexcept`, and `start` is too. Errors travel through `set_error`, not through exceptions thrown out of `start`. The operation state holds the receiver by value. Because `sync_wait` keeps the operation state on its own stack frame until completion, nothing here is heap-allocated.

## Where work runs: schedulers

A **scheduler** is a lightweight handle to an execution resource such as a thread pool, an event loop, or a GPU stream. Its only required operation is `schedule(sch)`, which returns a sender that completes on that resource. Standard schedulers include `run_loop`'s scheduler (the loop `sync_wait` drives), `inline_scheduler`, `task_scheduler` (a type-erased scheduler), and `parallel_scheduler`, obtained from `get_parallel_scheduler()`, which guarantees parallel forward progress and has a replaceable backend.

Three adaptors move work between schedulers, and they differ in where the **continuation** runs:

| Adaptor | Starts the work on | Code after it runs on |
| --- | --- | --- |
| `starts_on(sch, s)` | `sch` | wherever `s` completed, normally `sch` |
| `s \| continues_on(sch)` | wherever `s` starts | `sch` |
| `on(sch, s)` | `sch` | the scheduler the whole operation was started on |

`on` is the one to reach for when you want to "run this over there and come back". It finds that resource through the receiver's environment, so under `sync_wait` it returns to the `run_loop` on the waiting thread.

```cpp
#include <execution>
#include <thread>

namespace ex = std::execution;

bool continuation_on_caller(ex::scheduler auto pool, bool use_on) {
  auto caller = std::this_thread::get_id();
  auto here = [caller] { return std::this_thread::get_id() == caller; };
  if (use_on) {
    auto [b] = std::this_thread::sync_wait(ex::on(pool, ex::just()) | ex::then(here)).value();
    return b;                          // true: on() transferred back to sync_wait's run_loop
  }
  auto [b] = std::this_thread::sync_wait(ex::starts_on(pool, ex::just()) | ex::then(here)).value();
  return b;                            // false when pool is a thread pool: then ran on the pool
}
```

Algorithms ask a sender's attributes and a receiver's environment for things like the completion scheduler, the stop token, and an allocator, through queries such as `get_completion_scheduler<set_value_t>`, `get_stop_token`, and `get_allocator`. `read_env(q)` is a sender that completes with the value of query `q` in the current environment, and `write_env(s, env)` changes the environment seen by `s`.

## Cancellation and structured lifetimes

Cancellation is cooperative. A receiver's environment carries a stop token. An operation that can be cancelled checks it or registers a callback, and when stop is requested it completes with `set_stopped`. `when_all` gives its children an `inplace_stop_token` of its own, and requests stop on it as soon as one child fails. `unstoppable(s)` hides the stop token from `s`.

Because every operation completes exactly once and children finish before parents, there is no "fire and forget" in the core model. Work that should outlive the current scope must be **associated** with an async scope. A `counting_scope` counts the operations associated with it. `spawn(s, scope.get_token())` starts `s` eagerly inside the scope, and `spawn_future` does the same but returns a sender for the result. `scope.join()` is a sender that completes when every associated operation has finished. This is what replaced `start_detached` and `ensure_started`, which let work escape without anybody waiting for it.

> **Pitfall.** Destroying a `counting_scope` that has been used but not joined calls `std::terminate`, even if its operations happen to have finished. Before it goes out of scope, `close()` it and wait for `scope.join()`, with `sync_wait` or `co_await`.

Coroutines integrate in both directions. Inside a coroutine whose promise uses `with_awaitable_senders`, `co_await s` suspends until `s` completes and produces its value. An error is thrown, and a stop ends the coroutine without resuming it. `std::execution::task<T>`, from P3552, is a lazy coroutine type that is itself a sender. Its default error completion is `set_error_t(std::exception_ptr)`, it carries an `inplace_stop_token`, and by default it resumes on the scheduler it was started on.

## What is available today

| Implementation | Status |
| --- | --- |
| GCC 16 libstdc++ | No sender support. `__cpp_lib_senders` is not defined. |
| Clang 21 libc++ | No sender support. |
| NVIDIA stdexec | Reference implementation in namespace `stdexec`, tracking the draft closely. |
| Beman `execution` and `task` | Implementations of the C++26 wording from the Beman project. |

The tested stdexec revision differs from N5050 in small ways. Its `sync_wait` lives in `stdexec`, not in `std::this_thread`. Its `exec` namespace still provides `ensure_started`, `start_detached`, and `split` as extensions, along with `exec::static_thread_pool`. None of the code on this page uses those extensions.

## What to remember

- Senders are lazy descriptions. Nothing runs until `connect` and `start`, usually done for you by `sync_wait`, `spawn`, or `co_await`.
- Every operation completes exactly once, on one of three channels: value (any number of arguments), error (exactly one), or stopped (none).
- The operation state must outlive the operation, and destroying it early is undefined behaviour.
- `then` maps values to a value, and `let_value` maps values to a new sender that it runs. Returning a sender from `then` does not run it.
- `sync_wait` needs exactly one value signature. It returns `optional<tuple<...>>`, gives an empty optional when stopped, and throws on error, turning an `error_code` into `system_error`.
- `starts_on` changes where work begins, `continues_on` changes where the continuation runs, and `on` goes over and comes back.
- Detached work goes through an async scope such as `counting_scope`. `ensure_started` and `start_detached` are gone.
- GCC 16 and Clang 21 do not ship it. Use stdexec or Beman.

## Concept Map Outline

- **Senders and receivers:** C++26 std::execution (P2300 and follow-ups): lazy, composable asynchronous work with structured lifetimes.
  - **Core contract:** The rules in [exec.async.ops] that every sender, receiver and algorithm obeys.
    - **Lazy senders:** A sender only describes work; nothing runs until connect and start.
    - **Three channels:** Complete exactly once: set_value with any arguments, set_error with one, set_stopped with none.
    - **Operation state lifetime:** Destroying it before completion is undefined behaviour; library op states cannot be copied or moved.
    - **Completion signatures:** Computed at compile time by a static consteval member; errors are constexpr exceptions (P3557).
  - **Algorithms:** Factories start chains, adaptors transform them, and all adaptors are pipeable.
    - **just and friends:** just, just_error and just_stopped complete immediately on one channel.
    - **then vs let_value:** then sends the callable's result; let_value runs the sender the callable returns.
    - **when_all:** Concatenates child values; on error or stop it requests stop on the other children.
    - **Reshaping:** into_variant, stopped_as_optional, stopped_as_error, upon_error and the bulk family.
  - **Consumers:** Ways to actually connect and start a sender.
    - **sync_wait:** Blocks, returns optional<tuple<...>>, empty when stopped; needs exactly one value signature.
    - **Errors become exceptions:** exception_ptr is rethrown, error_code becomes system_error, other errors are thrown as is.
    - **co_await and task:** Senders are awaitable; std::execution::task<T> (P3552) is a lazy coroutine that is a sender.
  - **Schedulers:** Handles to execution resources; schedule(sch) completes on that resource.
    - **starts_on:** Starts the work on a scheduler; the continuation stays wherever the work completed.
    - **continues_on:** Moves the continuation onto a scheduler after the predecessor completes.
    - **on:** Goes to a scheduler for the work, then transfers back to where it was started.
    - **parallel_scheduler:** From get_parallel_scheduler() (P2079): parallel forward progress, replaceable backend.
  - **Cancellation and scopes:** Cooperative stopping and structured ownership of background work.
    - **Stop tokens:** Read from the receiver's environment; when_all supplies its own inplace_stop_token.
    - **counting_scope:** spawn and spawn_future associate work with a scope; join() waits for all of it (P3149).
    - **Removed: ensure_started:** P3187 removed ensure_started and start_detached; split is not in C++26 either.
  - **Availability:** Status of implementations in late 2026.
    - **No GCC or Clang:** libstdc++ 16 and libc++ 21 do not define __cpp_lib_senders.
    - **stdexec and Beman:** NVIDIA stdexec and the Beman project implement the draft outside namespace std.

## Standardese Quiz Questions

### Question 1 [warmup] ([exec.async.ops], [exec.then])

Under the C++26 draft, what does this program print?

```cpp
#include <execution>
#include <cstdio>

namespace ex = std::execution;

int main() {
  auto work = ex::just() | ex::then([] { std::puts("A"); });
  std::puts("B");
  (void)work;
}
```

A. `A` then `B`
B. `B` only
C. `B` then `A`
D. Either order, because `then` runs on an unspecified thread

**Answer (B):** `B` only

**Why:** Senders are lazy. `just() | then(f)` only builds a description of the work, and `f` runs only after the sender is connected to a receiver and the operation state is started. Nothing here does that, because there is no `sync_wait`, `spawn`, or `co_await`. So only `B` is printed, and `work` is destroyed without ever running. This is the main difference from `std::async`, which starts work immediately.

### Question 2 [warmup] ([exec.sync.wait], [exec.just])

Under the C++26 draft, what is the type of `r`?

```cpp
#include <execution>

auto r = std::this_thread::sync_wait(std::execution::just(1, 2.0));
```

A. `std::optional<std::tuple<int, double>>`
B. `std::tuple<int, double>`
C. `std::variant<std::tuple<int, double>>`
D. `std::expected<std::tuple<int, double>, std::exception_ptr>`

**Answer (A):** `std::optional<std::tuple<int, double>>`

**Why:** `sync_wait` returns `optional` of a tuple of the decayed value types of the sender's single value completion. The tuple holds all values, because a value completion can carry any number of arguments. The optional is empty when the sender completes with `set_stopped`, and errors are thrown rather than returned, so there is no `expected`. The `variant` form is what `sync_wait_with_variant` returns.

### Question 3 [warmup] ([exec.sync.wait], [exec.async.ops])

A sender has completion signatures `set_value_t(int)`, `set_error_t(std::error_code)` and `set_stopped_t()`. At run time it completes with `set_stopped`. What does `std::this_thread::sync_wait` do?

A. It throws `std::system_error`
B. It calls `std::terminate`
C. It returns an empty `std::optional`
D. It blocks forever, because no value ever arrives

**Answer (C):** It returns an empty `std::optional`

**Why:** The stopped channel means that the work was cancelled, which is not an error, so `sync_wait` reports it as a disengaged `optional`. Throwing `std::system_error` is what happens on the error channel when the error is a `std::error_code`. Every started operation completes exactly once, so `sync_wait` always returns or throws.

### Question 4 [tricky] ([exec.then], [exec.let])

Under the C++26 draft, what is true of `r`?

```cpp
#include <execution>

namespace ex = std::execution;

auto r = std::this_thread::sync_wait(
    ex::just() | ex::then([] { return ex::just(42); }));
```

A. It is an `optional<tuple<int>>` holding `42`
B. It is ill-formed: the callable given to `then` may not return a sender
C. It is an `optional` holding a tuple whose element is the sender returned by the lambda, and the value 42 is never produced
D. Undefined behavior: the inner sender is destroyed without being started

**Answer (C):** It is an `optional` holding a tuple whose element is the sender returned by the lambda, and the value 42 is never produced

**Why:** `then` sends whatever its callable returns as a value, and a sender is just an object, so the result is a tuple holding a `just(42)` sender that nobody connects or starts. Destroying a sender that was never connected is fine, so there is no undefined behaviour. To run the returned sender and forward its completion, use `let_value`, which turns the same code into an `optional<tuple<int>>` holding 42.

### Question 5 [tricky] ([exec.sync.wait], [exec.just])

Under the C++26 draft, what happens with this code?

```cpp
#include <execution>

int main() {
  auto r = std::this_thread::sync_wait(std::execution::just_stopped());
  return r.has_value();
}
```

A. It is ill-formed: `sync_wait` mandates exactly one value completion signature, and `just_stopped()` has none
B. It returns 0, because `r` is an empty optional
C. It throws `std::system_error` with `errc::operation_canceled`
D. Undefined behavior: a stopped completion has no value to store

**Answer (A):** It is ill-formed: `sync_wait` mandates exactly one value completion signature, and `just_stopped()` has none

**Why:** `sync_wait` needs a single value completion signature to name its `optional<tuple<...>>` return type. `just_stopped()` has only `set_stopped_t()`, so the result type is ill-formed and the call violates a Mandates element. The empty-optional answer would be correct for a sender that may complete with a value but stops at run time. The same rule rejects a sender with two value signatures, which needs `sync_wait_with_variant`.

### Question 6 [tricky] ([exec.on], [exec.starts.on], [exec.continues.on], [exec.sync.wait])

`pool` is a scheduler for a thread pool whose threads are all distinct from the calling thread. In `std::this_thread::sync_wait(X | std::execution::then(f))`, which choice of `X` makes `f` run on the thread that called `sync_wait`?

A. `std::execution::starts_on(pool, std::execution::just())`
B. `std::execution::just() | std::execution::continues_on(pool)`
C. `std::execution::schedule(pool)`
D. `std::execution::on(pool, std::execution::just())`

**Answer (D):** `std::execution::on(pool, std::execution::just())`

**Why:** `on(sch, sndr)` starts `sndr` on `sch` and, when it completes, transfers execution back to the resource the `on` sender was started on. Under `sync_wait`, that is the `run_loop` driven by the waiting thread. `starts_on` begins on the pool and leaves the completion there. `continues_on(pool)` and `schedule(pool)` both complete on the pool, so `f` runs on a pool thread in all three cases.

### Question 7 [standardese] ([exec.opstate.general], [exec.async.ops])

A program connects a library sender to a receiver, calls `start` on the operation state, and then lets the operation state go out of scope before any completion function has been called. Under the C++26 draft, what is the status of this program?

A. The operation is cancelled, and the receiver gets `set_stopped`
B. Undefined behavior
C. The destructor blocks until the operation completes
D. It is ill-formed

**Answer (B):** Undefined behavior

**Why:** [exec.opstate.general] says that if an operation state object is destroyed during the lifetime of its asynchronous operation, the behaviour is undefined. The operation state is where the running work keeps its data, so nothing is cancelled and nothing waits. It is not ill-formed, because the compiler cannot know when the operation will complete. What is ill-formed is copying or moving an operation state created from a library-provided sender.

### Question 8 [standardese] ([execution.syn], [exec.counting.scopes], [exec.spawn.future], [exec.stopped.opt])

Which of these names is NOT declared in namespace `std::execution` by N5050, the final C++26 draft?

A. `ensure_started`
B. `counting_scope`
C. `spawn_future`
D. `stopped_as_optional`

**Answer (A):** `ensure_started`

**Why:** P3187R1 removed `ensure_started` and `start_detached`, because they let work escape without anyone waiting for it, which breaks structured concurrency. Their role is taken by async scopes from P3149: `counting_scope`, `spawn` and `spawn_future`. `stopped_as_optional` is a standard adaptor that turns a stopped completion into an empty optional value. Reference implementations such as stdexec still offer `ensure_started` as an extension, which is why it may look familiar.
