From 8fc64946631c3e42342f180ec0ef87a742591ee9 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 9 Jan 2024 12:49:49 -0800 Subject: [PATCH 01/89] respecify `split` and `ensure_started` in terms of `basic-sender` (#173) * [WIP] respecify `split` and `ensure_started` in terms of `basic-sender` * moar split and ensure_started * delete whitespace at the ends of lines * tidy * strike bit about copying the input sender's attributes --- execution.bs | 604 ++++++++++++++++++++++++++++----------------------- 1 file changed, 335 insertions(+), 269 deletions(-) diff --git a/execution.bs b/execution.bs index 81eb8e4..fbd2dc8 100644 --- a/execution.bs +++ b/execution.bs @@ -5059,6 +5059,10 @@ enum class forward_progress_guarantee { template<class T, class... Us> concept one-of = (same_as<T, Us> ||...); // exposition only + template<class Tag> + concept completion-tag = // exposition only + one-of<Tag, set_value_t, set_error_t, set_stopped_t>; + template<template<class...> class T, class... Args> concept well-formed = requires { typename T<Args...>; }; // exposition only @@ -5094,7 +5098,7 @@ enum class forward_progress_guarantee { using tag_t = tag_of_t<Sndr>; // exposition only using receiver_concept = receiver_t; - template<one-of<set_value_t, set_error_t, set_stopped_t> Tag, class... Args> + template<completion-tag Tag, class... Args> requires cpo-callable<impls-for<tag_t>::complete, Index, state-type<Sndr, Rcvr>&, Rcvr&, Tag, Args...> friend void tag_invoke(Tag, basic-receiver&& self, Args&&... args) noexcept { @@ -5248,7 +5252,7 @@ enum class forward_progress_guarantee { Index, auto& state, Rcvr& rcvr, Tag, Args&&... args) noexcept -> void requires callable<Tag, Rcvr, Args...> { // Mandates: Index::value == 0 - Tag()(std::move(rcvr), std::forward<Args>(args)...); + Tag()(std::move(rcvr), std::forward<Args>(args)...); } @@ -5660,8 +5664,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. The name `connect` denotes a customization point object. For subexpressions `sndr` and `rcvr`, let `Sndr` be `decltype((sndr))` and `Rcvr` be `decltype((rcvr))`, and let - `DS` and `DR` be the decayed types of `Sndr` and `Rcvr`, respectively. - + `DS` and `DR` be the decayed types of `Sndr` and `Rcvr`, respectively. + 3. Let connect-awaitable-promise be the following class:
@@ -5712,7 +5716,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
 5. Let `V` name the type await-result-type<DS,
     connect-awaitable-promise>, let `Sigs` name the type:
-    
+
     
     completion_signatures<
       SET-VALUE-SIG(V), // see [exec.snd.concepts]
@@ -6085,7 +6089,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     subexpressions `sch` and `sndr`, let `Sch` be `decltype((sch))` and `Sndr` be
     `decltype((sndr))`. If `Sch` does not satisfy `scheduler`, or `Sndr` does not
     satisfy `sender`, `schedule_from` is ill-formed.
-    
+
 3. Otherwise, the expression `schedule_from(sch, sndr)` is expression-equivalent
     to:
 
@@ -6226,7 +6230,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     `decltype((sndr))` and let `F` be the decayed type of `f`. If `Sndr` does not
     satisfy `sender`, or `F` does not satisfy movable-value,
     then-cpo(sndr, f) is ill-formed.
-    
+
 3. Otherwise, the expression then-cpo(sndr, f) is
     expression-equivalent to:
 
@@ -6493,142 +6497,353 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
       - propagates all completion operations sent by `sndr`.
 
-#### `execution::split` [exec.split] #### {#spec-execution.senders.adapt.split}
+#### `execution::split` and `execution::ensure_started` [exec.split] #### {#spec-execution.senders.adapt.split}
 
-1. `split` adapts an arbitrary sender into a sender that can be connected multiple times.
+1. `split` adapts an arbitrary sender into a sender that can be connected
+    multiple times. `ensure_started` eagerly starts the execution of a sender,
+    returning a sender that is usable as input to additional sender algorithms.
 
-2. Let split-env be the type of an environment such that,
-    given an instance `env`, the expression `get_stop_token(env)` is well-formed and
-    has type `stop_token`.
+2. Let shared-env be the type of an environment such that,
+    given an instance `env`, the expression `get_stop_token(env)` is well-formed
+    and has type `in_place_stop_token`.
 
-3. The name `split` denotes a customization point object. For some
-    subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If
-    sender_in<Sndr, split-env> or
-    `constructible_from>, env_of_t>` is `false`,
-    `split` is ill-formed. Otherwise, the expression
-    `split(sndr)` is expression-equivalent to:
+3. The names `split` and `ensure_started` denote customization point objects.
+    Let the expression `shared-cpo` be one of `split` or
+    `ensure_started`. For a subexpression `sndr`, let `Sndr` be
+    `decltype((sndr))`. If sender_in<Sndr, shared-env> or
+    `constructible_from>, env_of_t>` is `false`,
+    shared-cpo(sndr) is ill-formed.
+
+    
Although it has not yet been approved by LEWG, there + is a bug in the current wording that makes it impossible to safely copy the + attributes of a sender; it may have reference semantics, leading to a + dangling reference. I am striking this part for now and will bring a fix to + LEWG.
+ +4. Otherwise, the expression shared-cpo(sndr) is + expression-equivalent to:
       transform_sender(
         get-domain-early(sndr),
-        make-sender(split, {}, sndr));
+        make-sender(shared-cpo, {}, sndr));
       
- 1. Let `sndr` be a subexpression such that `Sndr` is `decltype((sndr))`, and let - `env...` be a pack of subexpressions such that `sizeof...(env) <= 1` is - `true`. If sender-for<Sndr, split_t> is `false`, - then the expression `split.transform_sender(sndr, env...)` is ill-formed; - otherwise, it returns a sender `sndr2` that: +5. Let `local-state` denote the following exposition-only class: - 1. Creates an object `sh_state` that contains a `stop_source`, a list of - pointers to operation states awaiting the completion of `sndr`, and that - also reserves space for storing: +
+    struct local-state-base {
+      virtual ~local-state-base() = default;
+      virtual void notify() noexcept = 0;
+      virtual void detach() noexcept = 0;
+      local-state-base* next{nullptr};
+    };
 
-            * the operation state that results from connecting `sndr` with `rcvr` described below, and
-            * the sets of values and errors with which `sndr` can complete, with
-                the addition of `exception_ptr`.
-            * the result of decay-copying `get_env(sndr)`.
+    template<class Sndr, class Rcvr>
+    struct local-state : local-state-base {
+      using on-stop-request = see below;
+      using on-stop-callback = typename stop_token_of_t<env_of_t<Rcvr>>::
+                                  template callback_type<on-stop-request>;
 
-        2. Constructs a receiver `rcvr` such that:
+      local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
+      ~local-state();
 
-            1. When `set_value(rcvr, args...)` is called, decay-copies
-                the expressions `args...` into `sh_state`. It then notifies all
-                the operation states in `sh_state`'s list of operation states
-                that the results are ready. If any exceptions are thrown, the
-                exception is caught and `set_error(rcvr,
-                current_exception())` is called instead.
+      void notify() noexcept override;
+      void detach() noexcept override;
 
-            2. When `set_error(rcvr, err)` is called, decay-copies `err`
-                into `sh_state`. It then notifies the operation states in
-                `sh_state`'s list of operation states that the results are ready.
+      optional<on-stop-callback> on_stop;
+      shared-state<Sndr>* sh_state;
+      Rcvr* rcvr;
+    };
+    
- 3. When `set_stopped(rcvr)` is called, notifies the - operation states in `sh_state`'s list of operation states that - the results are ready. + 1. Let `on-stop-request` denote the following exposition-only class: - 4. `get_env(rcvr)` is an expression env of type - split-env such that - get_stop_token(env) is well-formed - and returns the results of calling `get_token()` on `sh_state`'s - stop source. +
+        struct on-stop-request {
+          in_place_stop_source& stop_src;
+          void operator()() noexcept { stop_src.request_stop(); }
+        };
+        
- 3. Calls `get_env(sndr)` and decay-copies the result into - `sh_state`. + 2.
+        local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
- 4. Calls `connect(sndr, rcvr)`, resulting in an operation state - `op_state2`. `op_state2` is saved in `sh_state`. + 1. *Effects:* Equivalent to: - 5. When `sndr2` is connected with a receiver `out_rcvr` of type `OutRcvr`, it - returns an operation state object `op_state` that contains: +
+            auto&& [tag, data, child] = std::forward<Sndr>(sndr);
+            sh_state = data.sh_state.get();
+            sh_state->inc-ref();
+            this->rcvr = &rcvr;
+            
- * An object `out_rcvr2` of type `OutRcvr` decay-copied from `out_rcvr`, - * A reference to `sh_state`, - * A stop callback of type - optional<stop_token_of_t<env_of_t<OutRcvr>>::callback_type<stop-callback-fn>>, - where stop-callback-fn is the unspecified - class type: + 3.
+        ~local-state();
-
-                struct stop-callback-fn {
-                  stop_source& stop_src_;
-                  void operator()() noexcept {
-                    stop_src_.request_stop();
-                  }
-                };
-                
+ 1. *Effects:* Equivalent to: - 6. When `start(op_state)` is called: +
+            detach();
+            sh_state->dec-ref();
+            
- * If one of `rcvr`'s completion functions has executed, then let - Tag be the completion function that was - called. Calls Tag(out_rcvr2, args2...), - where `args2...` is a pack of const lvalues referencing the - subobjects of `sh_state` that have been saved by the original - call to Tag(rcvr, args...) and returns. + 4.
+        void notify() noexcept override;
- * Otherwise, it emplace constructs the stop callback optional with - the arguments `get_stop_token(get_env(out_rcvr2))` and - stop-callback-fn{stop-src}, where - stop-src refers to the stop source of - `sh_state`. - - * Otherwise, it adds a pointer to `op_state` to the list of - operation states in `sh_state`. If `op_state` is the first such - state added to the list: - - * If stop-src.stop_requested() is `true`, - all of the operation states in `sh_state`'s list of operation - states are notified as if `set_stopped(rcvr)` had - been called. - - * Otherwise, `start(op_state2)` is called. - - 7. When `rcvr` completes it will notify `op_state` that the result are - ready. Let Tag be whichever - completion function was called on receiver `rcvr`. `op_state`'s - stop callback optional is reset. Then - Tag(std::move(out_rcvr2), args2...) is called, - where `args2...` is a pack of const lvalues referencing the subobjects of - `sh_state` that have been saved by the original call to - Tag(rcvr, args...). - - 8. Ownership of `sh_state` is shared by `sndr2` and by every `op_state` - that results from connecting `sndr2` to a receiver. - - 2. Given subexpressions `sndr2` where `sndr2` is a sender returned from `split` - or a copy of such, `get_env(sndr2)` shall return an lvalue reference to the - object in `sh_state` that was initialized with the result of `get_env(sndr)`. - -5. Let `sndr` be a sender expression, `rcvr` be an instance of the receiver type - described above, `sndr2` be a sender returned from `split(sndr)` or a copy of - such, `rcvr2` is the receiver to which `sndr2` is connected, and `args` is the - pack of subexpressions passed to `rcvr`'s completion function - CSO when `sndr` completes. `sndr2` shall invoke - CSO(rcvr2, args2...) where `args2` is a pack of const - lvalue references to objects decay-copied from `args`, or by calling - set_error(rcvr2, err2) for some subexpression `err2`. The objects - passed to `rcvr2`'s completion operation shall be valid until after the - completion of the invocation of `rcvr2`'s completion operation. + 1. *Effects:* Equivalent to: + +
+            on_stop.reset();
+            visit(
+              [this]<class Tuple>(Tuple&& tupl) noexcept -> void {
+                apply(
+                  [this](auto tag, auto&... args) noexcept -> void {
+                    tag(std::move(*rcvr), std::forward_like<Tuple>(args)...);
+                  },
+                  tupl);
+              },
+              QUAL(sh_state->result));
+            )
+            
+ + where `QUAL` is `std::move` if `tag_of_t` is + `ensure-started-impl-tag`, and `as_const` otherwise. + + 5.
+        void detach() noexcept override;
+ + 1. *Effects:* Equivalent to sh_state->detach() + if `tag_of_t` is `ensure-started-impl-tag`; otherwise, + nothing. + +6. Let `shared-receiver` denote the following exposition-only class + template: + +
+    template<class Sndr>
+    struct shared-receiver {
+      using receiver_concept = receiver_t;
+
+      template<completion-tag Tag, class... Args>
+      friend void tag_invoke(Tag, shared-receiver&& self, Args&&... args) noexcept {
+        try {
+          using tuple_t = decayed-tuple<Tag, Args...>;
+          self.sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
+        } catch (...) {
+          using tuple_t = tuple<set_error_t, exception_ptr>;
+          self.sh_state->result.template emplace<tuple_t>(set_error, current_exception());
+        }
+        self.sh_state->notify();
+      }
+
+      friend decltype(auto) tag_invoke(get_env_t, const shared-receiver& self) noexcept {
+        return MAKE-ENV(get_stop_token, self.sh_state->stop_src.get_token());
+      }
+
+      shared-state<Sndr>* sh_state;
+    };
+    
+ +7. Let `shared-state` denote the following exposition-only class + template: + +
+    template<class Sndr>
+    struct shared-state {
+      using variant-type = see below;
+
+      explicit shared-state(Sndr&& sndr);
+
+      void start-op() noexcept;
+      void notify() noexcept;
+      void detach() noexcept;
+      void dec-ref() noexcept;
+      void inc-ref() noexcept { ref_count.fetch_add(1, memory_order_relaxed); }
+
+      in_place_stop_source stop_src{};
+      variant-type result{};
+      atomic<void*> head{nullptr};
+      atomic<size_t> ref_count{1};
+      connect_result_t<Sndr, shared-receiver<Sndr>> op_state2;
+    };
+    
+ + 1. Let `Sigs` be a pack of the arguments to the + `completion_signatures` specialization named by + `completion_signatures_of_t`. Let `as-tuple` be an + alias template such that + as-tuple<Tag(Args...)> denotes the type + decayed-tuple<Tag, Args...>. Then + `variant-type` denotes the type + variant<tuple<set_stopped_t>, tuple<set_error_t, + exception_ptr>, as-tuple<Sigs>...>, but with + duplicate types removed. + + 2.
+          explicit shared-state(Sndr&& sndr);
+ + 1. *Effects:* Initializes `op_state2` with the result of + connect(std::forward<Sndr>(sndr), shared-receiver{this}). + + 3.
+          void start-op() noexcept;
+ + 1. *Effects:* inc-ref(). If + `stop_src.stop_requested()` is `true`, calls + notify(); otherwise, calls + `start(op_state2)`. + + 4.
+          void notify() noexcept;
+ + 1. *Effects:* Atomically exchanges the current value of `head` with + `this` and saves the previous value in a local variable `state` of + type local-state-base*. While `state` is not + `nullptr`, calls state->notify(), then sets + `state` to `state->next`. Finally, calls + dec-ref(). + + 5.
+          void detach() noexcept;
+ + 1. *Effects:* Atomically reads the value of `head`. If it is `nullptr`, + calls `stop_src.request_stop()`. This has + the effect of requesting early termination of any asynchronous + operation that was started as a result of a call to `ensure_started`, + but only if the resulting sender was never connected and started. + + + 5.
+          void dec-ref() noexcept;
+ + 1. *Effects:* Atomically decrements `ref_count`. If the new value of + `ref_count` is `0`, calls `delete this`. + +8. For each type `split_t` and `ensure_started_t`, there is a different, + associated exposition-only implementation tag type, `split-impl-tag` + and `ensure-started-impl-tag`, respectively. Let + `shared-impl-tag` be the associated implementation tag type of + `shared-cpo`. Given an expression `sndr`, let `Sndr` be + `decltype((sndr))`. The expression + shared-cpo.transform_sender(sndr) is equivalent to: + +
+      auto&& [tag, data, child] = sndr;
+      auto* sh_state = new shared-state{std::forward_like<Sndr>(child)};
+      return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
+      
+ + where `shared-wrapper` is the exposition-only class template: + +
+      struct dec-ref { // exposition only
+        void operator()(auto* ptr) const noexcept { ptr->dec-ref(); }
+      };
+
+      template<class Sndr, class Tag>
+      struct shared-wrapper { // exposition only
+        unique_ptr<shared-state<Sndr>, dec-ref> sh_state; // exposition only
+
+        shared-wrapper(shared-state<Sndr>* ptr, Tag) noexcept : sh_state(ptr) {
+          if constexpr (same_as<Tag, ensure_started_t>) sh_state->start-op();
+        }
+
+        shared-wrapper(shared-wrapper&&) noexcept = default;
+        shared-wrapper(const shared-wrapper& other) noexcept
+          requires same_as<Tag, split_t> : sh_state(other.sh_state.get()) {
+          if (sh_state) sh_state->inc-ref();
+        }
+
+        ~shared-wrapper() {
+          if constexpr (same_as<Tag, ensure_started_t>)
+            if (sh_state) sh_state->detach();
+        }
+
+        shared-wrapper& operator=(shared-wrapper other) noexcept {
+          other.sh_state.swap(sh_state);
+          return *this;
+        }
+      };
+      
+ +9. The exposition-only class template impls-for + ([exec.snd.general]) is specialized for shared-impl-tag + as follows: + +
+        template<>
+        struct impls-for<shared-impl-tag> : default-impls {
+          static constexpr auto get-state = see below;
+          static constexpr auto start = see below;
+        };
+        
+ + 1. The member + impls-for<shared-impl-tag>::get-state + is initialized with a callable object equal to the following lambda: + +
+          []<class Sndr>(Sndr&& sndr, auto& rcvr) noexcept {
+            return local-state{std::forward<Sndr>(sndr), rcvr};
+          }
+          
+ + 2. The member + impls-for<shared-impl-tag>::start + is initialized with a callable object that has a call operator + equivalent to the following: + +
+        template <class Sndr, class Rcvr>
+        void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
+ + 1. *Effects:* + + - Atomically reads the value of `state.sh_state->head` into a + local variable `old_head` of type `void*`. + + - If `old_head` is not equal to `state.sh_state`: + + - Calls: + +
+                    state.on_stop.emplace(
+                      get_stop_token(get_env(rcvr)),
+                      on-stop-request{state.sh_state->stop_src})
+                    
+ + - If `shared-impl-tag` is + `ensure-started-impl-tag`, and if + `state.sh_state->stop_src.stop_requested()` + is `true`, calls `set_stopped(std::move(rcvr))` + and returns. + + `old_head` will be equal to `state.sh_state` + when the child asynchronous operation has already completed. + + - If `old_head` is equal to `state.sh_state`, calls + state.notify() and returns. + + - Atomically does the following: + writes `old_head` into `state.next`, and + exchanges `state.sh_state->head` with `&state`. + This is typically done by executing + this step and the previous in an atomic compare-and-exchange + loop until the exchange succeeds. + + - If `shared-impl-tag` is `split-impl-tag`, and + if `old_head` is equal to `nullptr`, calls + state.sh_state->start-op(). + +10. If a sender returned from `ensure_started` is + destroyed without being connected to a receiver, or if it is connected but + the operation state is destroyed without having been started, or if stop has + been requested on the receiver's stop token prior to `start` having been + called, then when the child operation completes and it releases its shared + ownership of the `shared-state` object, the `shared-state` + object will be destroyed and the results of the child operation are + discarded. #### `execution::when_all` [exec.when.all] #### {#spec-execution.senders.adaptor.when_all} @@ -6889,155 +7104,6 @@ template<class Domain, class Tag, sender Sndr, class... Args> [err = std::move(data)]() mutable { return just_error(std::move(err)); });
-#### `execution::ensure_started` [exec.ensure.started] #### {#spec-execution.senders.adapt.ensure_started} - -1. `ensure_started` eagerly starts the execution of a sender, returning a sender - that is usable as intput to additional sender algorithms. - -2. Let ensure-started-env be the type of an execution - environment such that, given an instance `env`, the expression - `get_stop_token(env)` is well-formed and has type `stop_token`. - -3. The name `ensure_started` denotes a customization point object. - For some subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If - sender_in<Sndr, ensure-started-env> or - `constructible_from>, env_of_t>` is - `false`, `ensure_started(sndr)` is ill-formed. Otherwise, the - expression `ensure_started(sndr)` is expression-equivalent to: - -
-    transform_sender(
-      get-sender-domain(sndr),
-      make-sender(ensure_started, {}, sndr))
-    
- - 1. Let `sndr` be a subexpression such that `Sndr` is `decltype((sndr))`, and let `env...` be a pack of - subexpressions such that sizeof...(env) <= 1 is `true`. - If sender-for<Sndr, ensure_started_t> is `false`, then the expression - `ensure_started.transform_sender(sndr, env...)` is ill-formed; otherwise, it returns - a sender `sndr2`, that: - - 1. Creates an object `sh_state` that contains a `stop_source`, an - initially null pointer to an operation state awaitaing completion, - and that also reserves space for storing: - - * the operation state that results from connecting `sndr` with `rcvr` described below, and - * the sets of values and errors with which `sndr` can complete, with - the addition of `exception_ptr`. - * the result of decay-copying `get_env(sndr)`. - - `sndr2` shares ownership of `sh_state` with `rcvr` described below. - - 2. Constructs a receiver `rcvr` such that: - - 1. When `set_value(rcvr, args...)` is called, decay-copies - the expressions `args...` into `sh_state`. It then checks - `sh_state` to see if there is an operation state awaiting - completion; if so, it notifies the operation state that the - results are ready. If any exceptions are thrown, the exception - is caught and `set_error(rcvr, current_exception())` is - called instead. - - 2. When `set_error(rcvr, err)` is called, decay-copies `err` - into `sh_state`. If there is an operation state awaiting completion, - it then notifies the operation state that the results are ready. - - 3. When `set_stopped(rcvr)` is called, it then notifies any - awaiting operation state that the results are ready. - - 4. `get_env(rcvr)` is an expression env of type - ensure-started-env such that - get_stop_token(env) is well-formed - and returns the results of calling `get_token()` on `sh_state`'s - stop source. - - 5. `rcvr` shares ownership of `sh_state` with `sndr2`. After `rcvr` - has been completed, it releases its ownership of `sh_state`. - - 3. Calls `get_env(sndr)` and decay-copies the result into - `sh_state`. - - 4. Calls `connect(sndr, rcvr)`, resulting in an operation state - `op_state2`. `op_state2` is saved in `sh_state`. It then calls - `start(op_state2)`. - - 5. When `sndr2` is connected with a receiver `out_rcvr` of type `OutRcvr`, it - returns an operation state object `op_state` that contains: - - * An object `out_rcvr2` of type `OutRcvr` decay-copied from `out_rcvr`, - * A reference to `sh_state`, - * A stop callback of type - optional<stop_token_of_t<env_of_t<OutRcvr>>::callback_type<stop-callback-fn>>, - where stop-callback-fn is the unspecified - class type: - -
-                struct stop-callback-fn {
-                  stop_source& stop_src_;
-                  void operator()() noexcept {
-                    stop_src_.request_stop();
-                  }
-                };
-                
- - `sndr2` transfers its ownership of `sh_state` to `op_state`. - - 6. When `start(op_state)` is called: - - * If `rcvr` has already been completed, then let - CF be whichever completion function - was used to complete `rcvr`. Calls - CF(out_rcvr2, args2...), where `args2...` is a - pack of xvalues referencing the subobjects of `sh_state` that have - been saved by the original call to CF(rcvr, - args...) and returns. - - * Otherwise, it emplace constructs the stop callback optional with - the arguments `get_stop_token(get_env(out_rcvr2))` and - stop-callback-fn{stop-src}, where - stop-src refers to the stop source of - `sh_state`. - - * Then, it checks to see if - stop-src.stop_requested() is `true`. If so, it - calls `set_stopped(out_rcvr2)`. - - * Otherwise, it sets `sh_state` operation state pointer to the - address of `op_state`, registering itself as awaiting the result - of the completion of `rcvr`. - - 7. When `rcvr` completes it will notify `op_state` that the result are - ready. Let CF be whichever - completion function was used to complete `rcvr`. `op_state`'s stop - callback optional is reset. Then - CF(std::move(out_rcvr2), args2...) is called, - where `args2...` is a pack of xvalues referencing the subobjects of - `sh_state` that have been saved by the original call to - CF(rcvr, args...). - - 8. [*Note:* If sender `sndr2` is destroyed without being connected to a - receiver, or if it is connected but the operation state is destroyed - without having been started, then when `rcvr` - completes and it releases its shared ownership of `sh_state`, - `sh_state` will be destroyed and the results of the operation are - discarded. -- *end note*] - - 4. Given a subexpression `sndr`, let `sndr2` be the result of `ensure_started(sndr)`. - The result of `get_env(sndr2)` shall return an lvalue reference to the - object in `sh_state` that was initialized with the result of `get_env(sndr)`. - - 4. Let `sndr` be a sender expression, `rcvr` be an instance of the receiver type - described above, `sndr2` be a sender returned - from `ensure_started(sndr)` or a copy of such, `rcvr2` is the receiver - to which `sndr2` is connected, and `args` is the pack of subexpressions - passed to `rcvr`'s completion function CSO - when `sndr` completes. `sndr2` shall invoke CSO(rcvr2, args2...) where - `args2` is a pack of xvalue references to objects decay-copied from - `args`, or by calling set_error(rcvr2, err2) for some subexpression - `err2`. The objects passed to `rcvr2`'s completion operation shall - be valid until after the completion of the invocation of `rcvr2`'s completion - operation. - ### Sender consumers [exec.consumers] ### {#spec-execution.senders.consumers} #### `execution::start_detached` [exec.start.detached] #### {#spec-execution.senders.consumers.start_detached} @@ -7053,7 +7119,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     apply_sender(get-sender-domain(sndr), start_detached, sndr)
     
- + * Mandates: The type of the expression above is `void`. If the expression above does not eagerly start the sender `sndr` after From d87dfa14c806e5165c2d988e9d05c07ca7c094c1 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 4 Jan 2024 09:01:04 -0800 Subject: [PATCH 02/89] add an exposition-only utility for emplacing immovable types in containers --- execution.bs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/execution.bs b/execution.bs index fbd2dc8..e2e624e 100644 --- a/execution.bs +++ b/execution.bs @@ -5007,6 +5007,25 @@ enum class forward_progress_guarantee { [*Note:* The `transfer` algorithm is unique in that it ignores the execution domain of its predecessor, using only its destination scheduler to select a customization. *--end note*] + 11.
+        template<callable Fun>
+          requires is_nothrow_move_constructible_v<Fun>
+        struct emplace-construct { // exposition only
+          Fun fun; // exposition only
+          using type = call-result-t<Fun>;
+
+          constexpr operator type() && noexcept(nothrow-callable<Fun>) {
+            return std::move(fun)();
+          }
+
+          constexpr type operator()() && noexcept(nothrow-callable<Fun>) {
+            return std::move(fun)();
+          }
+        };
+        
+ + 1. `emplace-construct` is used to emplace + non-movable types into containers like `tuple`, `optional`, and `variant`. 11.
         template<class... T>

From caa84bbe51fee299aa80f0f829f611bd6323da5f Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Tue, 9 Jan 2024 16:16:16 -0800
Subject: [PATCH 03/89] rename to emplace-from

---
 execution.bs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/execution.bs b/execution.bs
index e2e624e..19a5548 100644
--- a/execution.bs
+++ b/execution.bs
@@ -5010,7 +5010,7 @@ enum class forward_progress_guarantee {
     11. 
         template<callable Fun>
           requires is_nothrow_move_constructible_v<Fun>
-        struct emplace-construct { // exposition only
+        struct emplace-from { // exposition only
           Fun fun; // exposition only
           using type = call-result-t<Fun>;
 
@@ -5024,7 +5024,7 @@ enum class forward_progress_guarantee {
         };
         
- 1. `emplace-construct` is used to emplace + 1. `emplace-from` is used to emplace non-movable types into containers like `tuple`, `optional`, and `variant`. 11.

From 6b8d6965219b4609eb067dc8717f7600bf72f167 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Tue, 9 Jan 2024 16:20:10 -0800
Subject: [PATCH 04/89] replace emplacer with emplace-from

---
 execution.bs | 15 +--------------
 1 file changed, 1 insertion(+), 14 deletions(-)

diff --git a/execution.bs b/execution.bs
index 19a5548..d452b17 100644
--- a/execution.bs
+++ b/execution.bs
@@ -5047,19 +5047,6 @@ enum class forward_progress_guarantee {
             structured binding declaration [dcl.struct.bind].
 
     12. 
-        template<callable Fn>
-        struct emplacer { // exposition only
-          Fn fn;  // exposition only
-          operator call-result-t<Fn> () && noexcept(nothrow-callable<Fn>) {
-            return std::move(fn)();
-          }
-        };
-        
- - 1. The type `emplacer` is used to emplace non-movable - types into containers like `tuple`, `optional`, and `variant`. - - 13.
         template <semiregular Tag, movable-value Data = see below, sender... Child>
         constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
@@ -6408,7 +6395,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> auto sndr2 = apply(std::move(state.fn), args); auto rcvr2 = receiver2{std::move(rcvr), std::move(state.env)}; auto mkop2 = [&] { return connect(std::move(sndr2), std::move(rcvr2)); }; - auto& op2 = state.ops2.emplace<decltype(mkop2())>(emplacer{mkop2}); + auto& op2 = state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2}); start(op2);
From 4155eff0ed82c6519e0a0d738a9e96136edc5d80 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sun, 28 Jan 2024 15:53:24 -0800 Subject: [PATCH 05/89] integrate feedback from the LWG 2024-01-24 wording review telecon --- execution.bs | 107 +++++++++++++++++++++++++++++---------------------- 1 file changed, 62 insertions(+), 45 deletions(-) diff --git a/execution.bs b/execution.bs index fbd2dc8..d516be0 100644 --- a/execution.bs +++ b/execution.bs @@ -4973,13 +4973,15 @@ enum class forward_progress_guarantee { constexpr auto get-domain-early(const Sndr& sndr) noexcept;
- 1. Effects: Equivalent to the first of the following that is well-formed: + 1. Effects: Equivalent to return Domain(); + where `Domain` is the decayed type of the first of the following + expressions that is well-formed: - - `return get_domain(get_env(sndr));` + - `get_domain(get_env(sndr))` - - return completion-domain(sndr); + - completion-domain(sndr) - - `return default_domain();` + - `default_domain()` 10.
         template<class Sndr, class Env>
@@ -4988,27 +4990,43 @@ enum class forward_progress_guarantee {
 
         1. Effects: Equivalent to:
 
-            - If sender-for<Sndr, transfer_t> is `true`, then
-                return query-or-default(get_domain, sch, default_domain()) where `sch`
-                is the scheduler that was used to construct `sndr`,
+            - If sender-for<Sndr, transfer_t> is `true`,
+                then return Domain(); where `Domain` is
+                the type of the following expression:
 
-            - Otherwise, `return get_domain(get_env(sndr));` if that expression is well-formed,
+                
+                [] {
+                  auto [ignore1, sch, ignore2] = sndr;
+                  return query-or-default(get_domain, sch, default_domain());
+                }();
+                
- - Otherwise, return completion-domain<X>(sndr); - if that expression is well-formed and its type is not *X* where - *X* is an unspecified type, + - Otherwise, return Domain(); where `Domain` is + the first of the following expressions that is well-formed and has class + type: - - Otherwise, `return get_domain(env);` if that expression is well-formed, + - `get_domain(get_env(sndr))` - - Otherwise, `return get_domain(get_scheduler(env));` if that expression is well-formed, + - completion-domain<void>(sndr) - - Otherwise, `return default_domain();`. + - `get_domain(env)` - [*Note:* The `transfer` algorithm is unique in that it ignores the execution domain of - its predecessor, using only its destination scheduler to select a customization. *--end note*] + - `get_domain(get_scheduler(env))` + - `default_domain()`. + + The `transfer` algorithm is unique in that it ignores the + execution domain of its predecessor, using only the domain of its + destination scheduler to select a customization. 11.
+        struct on-stop-request {
+          in_place_stop_source& stop_src;
+          void operator()() noexcept { stop_src.request_stop(); }
+        };
+        
+ + 12.
         template<class... T>
         struct product-type {
           using type0 = T0;      // exposition only
@@ -5027,7 +5045,7 @@ enum class forward_progress_guarantee {
             product-type is usable as the initializer of a
             structured binding declaration [dcl.struct.bind].
 
-    12. 
+    13. 
         template<callable Fn>
         struct emplacer { // exposition only
           Fn fn;  // exposition only
@@ -5040,7 +5058,7 @@ enum class forward_progress_guarantee {
         1. The type `emplacer` is used to emplace non-movable
             types into containers like `tuple`, `optional`, and `variant`.
 
-    13. 
+    14. 
         template <semiregular Tag, movable-value Data = see below, sender... Child>
         constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
@@ -6511,7 +6529,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> Let the expression `shared-cpo` be one of `split` or `ensure_started`. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If sender_in<Sndr, shared-env> or - `constructible_from>, env_of_t>` is `false`, + `constructible_from>, env_of_t>` is `false`, shared-cpo(sndr) is ill-formed.
Although it has not yet been approved by LEWG, there @@ -6542,7 +6560,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> template<class Sndr, class Rcvr> struct local-state : local-state-base { using on-stop-request = see below; - using on-stop-callback = typename stop_token_of_t<env_of_t<Rcvr>>:: + using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>:: template callback_type<on-stop-request>; local-state(Sndr&& sndr, Rcvr& rcvr) noexcept; @@ -6557,28 +6575,19 @@ template<class Domain, class Tag, sender Sndr, class... Args> };
- 1. Let `on-stop-request` denote the following exposition-only class: - -
-        struct on-stop-request {
-          in_place_stop_source& stop_src;
-          void operator()() noexcept { stop_src.request_stop(); }
-        };
-        
- - 2.
+    1. 
         local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
1. *Effects:* Equivalent to:
             auto&& [tag, data, child] = std::forward<Sndr>(sndr);
-            sh_state = data.sh_state.get();
-            sh_state->inc-ref();
+            this->sh_state = data.sh_state.get();
+            this->sh_state->inc-ref();
             this->rcvr = &rcvr;
             
- 3.
+    2. 
         ~local-state();
1. *Effects:* Equivalent to: @@ -6588,7 +6597,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> sh_state->dec-ref();
- 4.
+    3. 
         void notify() noexcept override;
1. *Effects:* Equivalent to: @@ -6604,17 +6613,20 @@ template<class Domain, class Tag, sender Sndr, class... Args> tupl); }, QUAL(sh_state->result)); - ) + );
- where `QUAL` is `std::move` if `tag_of_t` is - `ensure-started-impl-tag`, and `as_const` otherwise. + where `QUAL` is `std::move` if + same_as<tag_of_t<Sndr>, + ensure-started-impl-tag> is `true`, and `as_const` + otherwise. - 5.
+    4. 
         void detach() noexcept override;
- 1. *Effects:* Equivalent to sh_state->detach() - if `tag_of_t` is `ensure-started-impl-tag`; otherwise, + 1. *Effects:* Equivalent to sh_state->detach() if + same_as<tag_of_t<Sndr>, + ensure-started-impl-tag> is `true`; otherwise, nothing. 6. Let `shared-receiver` denote the following exposition-only class @@ -6658,14 +6670,14 @@ template<class Domain, class Tag, sender Sndr, class... Args> void start-op() noexcept; void notify() noexcept; void detach() noexcept; + void inc-ref() noexcept; void dec-ref() noexcept; - void inc-ref() noexcept { ref_count.fetch_add(1, memory_order_relaxed); } in_place_stop_source stop_src{}; variant-type result{}; atomic<void*> head{nullptr}; atomic<size_t> ref_count{1}; - connect_result_t<Sndr, shared-receiver<Sndr>> op_state2; + connect_result_t<Sndr, shared-receiver<Sndr>> op_state; };
@@ -6683,7 +6695,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2.
           explicit shared-state(Sndr&& sndr);
- 1. *Effects:* Initializes `op_state2` with the result of + 1. *Effects:* Initializes `op_state` with the result of connect(std::forward<Sndr>(sndr), shared-receiver{this}). 3.
@@ -6692,7 +6704,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           1. *Effects:* inc-ref(). If
               `stop_src.stop_requested()` is `true`, calls
               notify(); otherwise, calls
-              `start(op_state2)`.
+              `start(op_state)`.
 
       4. 
           void notify() noexcept;
@@ -6715,9 +6727,14 @@ template<class Domain, class Tag, sender Sndr, class... Args> 5.
+          void inc-ref() noexcept;
+ + 1. *Effects:* Increments `ref_count`. + + 6.
           void dec-ref() noexcept;
- 1. *Effects:* Atomically decrements `ref_count`. If the new value of + 1. *Effects:* Decrements `ref_count`. If the new value of `ref_count` is `0`, calls `delete this`. 8. For each type `split_t` and `ensure_started_t`, there is a different, From 066a8a98e27454add2cea7581fa69db3fb7d95c2 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 30 Jan 2024 09:54:39 -0800 Subject: [PATCH 06/89] Fix search-and-replace typo --- execution.bs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index fbd2dc8..980be2f 100644 --- a/execution.bs +++ b/execution.bs @@ -4050,8 +4050,8 @@ template<class C> let `c` be the completion operation set(rcvr, args...), and let `F` be the function type decltype(auto(set))(decltype((args))...). - A completion signature `Sndr` is associated with `c` if and only if - MATCHING-SIG(Sndr, F) is `true` ([exec.general]). Together, + A completion signature `Sig` is associated with `c` if and only if + MATCHING-SIG(Sig, F) is `true` ([exec.general]). Together, a sender type and an environment type `Env` determine the set of completion signatures of an asynchronous operation that results from connecting the sender with a receiver that has an environment of type `Env`. Date: Tue, 6 Feb 2024 09:22:39 -0800 Subject: [PATCH 07/89] escape a stray `<` that was getting treated as an HTML tag --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index fbd2dc8..f0fe3ef 100644 --- a/execution.bs +++ b/execution.bs @@ -7849,7 +7849,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> template<class Sndr, class Promise> // arguments are not associated entities ([lib.tmpl-heads]) class sender-awaitable { struct unit {}; - using value_t = single-sender-value-type<Sndr, env_of_t>; + using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>; using result_t = conditional_t<is_void_v<value_t>, unit, value_t>; struct awaitable-receiver; From e43b34ba70ea6e992b88dbc2a4072b0f7bbb5c07 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 6 Feb 2024 09:43:37 -0800 Subject: [PATCH 08/89] `when_all` should be awaitable and the result should be de-structure-able fixes #182 --- execution.bs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 708c870..0c9ce40 100644 --- a/execution.bs +++ b/execution.bs @@ -7841,7 +7841,9 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. Otherwise, if `value_types_of_t` would have the form `Variant>` or `Variant<>`, then single-sender-value-type<Sndr, Env> is an alias for type `void`. - 3. Otherwise, single-sender-value-type<Sndr, Env> is ill-formed. + 3. Otherwise, if `value_types_of_t` would have the form `Variant>` where `Ts` is a parameter pack, then single-sender-value-type<Sndr, Env> is an alias for type `std::tuple...>`. + + 4. Otherwise, single-sender-value-type<Sndr, Env> is ill-formed. 2. The type sender-awaitable<Sndr, Promise> is equivalent to the following: From 7f61cd06f76ba9d2eddf95b7c5e216cd7276a9d1 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 7 Feb 2024 12:08:45 -0800 Subject: [PATCH 09/89] dec_ref synchronization Co-authored-by: Lewis Baker --- execution.bs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/execution.bs b/execution.bs index 708c870..c38ae18 100644 --- a/execution.bs +++ b/execution.bs @@ -6719,6 +6719,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. *Effects:* Atomically decrements `ref_count`. If the new value of `ref_count` is `0`, calls `delete this`. + 2. *Synchronization:* If `dec_ref()` does not decrement the `ref_count` to `0` then synchronizes with + the call to `dec_ref()` that decrements `ref_count` to `0`. 8. For each type `split_t` and `ensure_started_t`, there is a different, associated exposition-only implementation tag type, `split-impl-tag` From e3f505484edc8c30bb744877f54ea92eaa8bd84b Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sun, 11 Feb 2024 16:45:48 -0800 Subject: [PATCH 10/89] integrate feedback from the LWG 2024-02-07 wording review telecon --- execution.bs | 79 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 33 deletions(-) diff --git a/execution.bs b/execution.bs index d516be0..af0bb5c 100644 --- a/execution.bs +++ b/execution.bs @@ -3195,7 +3195,7 @@ add the following new subclause with suggested stable name [lib.tmpl-heads]. - using S = typename s-impl<T>::type; + using S = s-impl<T>::type;
or as @@ -3210,7 +3210,7 @@ add the following new subclause with suggested stable name [lib.tmpl-heads]. struct s-impl { - using T = typename HiddenT::type; + using T = HiddenT::type; }; template<class T> @@ -3359,7 +3359,7 @@ template<class CB> class in_place_stop_callback; template<class T, class CB> - using stop_callback_for_t = typename T::template callback_type<CB>; + using stop_callback_for_t = T::template callback_type<CB>;
@@ -6547,6 +6547,11 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(shared-cpo, {}, sndr));
+ - The default implementation of `transform_sender` + will have the effect of connecting the sender to a receiver and, in the + case of `ensure_started`, calling `start` on the resulting operation + state. It will return a sender with a different tag type. + 5. Let `local-state` denote the following exposition-only class:
@@ -6741,13 +6746,12 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     associated exposition-only implementation tag type, `split-impl-tag`
     and `ensure-started-impl-tag`, respectively. Let
     `shared-impl-tag` be the associated implementation tag type of
-    `shared-cpo`. Given an expression `sndr`, let `Sndr` be
-    `decltype((sndr))`. The expression
+    `shared-cpo`. Given an expression `sndr`, the expression
     shared-cpo.transform_sender(sndr) is equivalent to:
 
       
       auto&& [tag, data, child] = sndr;
-      auto* sh_state = new shared-state{std::forward_like<Sndr>(child)};
+      auto* sh_state = new shared-state{std::forward_like<decltype((sndr))>(child)};
       return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
       
@@ -6763,13 +6767,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> unique_ptr<shared-state<Sndr>, dec-ref> sh_state; // exposition only shared-wrapper(shared-state<Sndr>* ptr, Tag) noexcept : sh_state(ptr) { - if constexpr (same_as<Tag, ensure_started_t>) sh_state->start-op(); - } - - shared-wrapper(shared-wrapper&&) noexcept = default; - shared-wrapper(const shared-wrapper& other) noexcept - requires same_as<Tag, split_t> : sh_state(other.sh_state.get()) { - if (sh_state) sh_state->inc-ref(); + if constexpr (same_as<Tag, ensure_started_t>) + sh_state->start-op(); } ~shared-wrapper() { @@ -6777,9 +6776,16 @@ template<class Domain, class Tag, sender Sndr, class... Args> if (sh_state) sh_state->detach(); } - shared-wrapper& operator=(shared-wrapper other) noexcept { - other.sh_state.swap(sh_state); - return *this; + shared-wrapper(shared-wrapper&&) noexcept = default; + shared-wrapper(const shared-wrapper& other) noexcept requires same_as<Tag, split_t> + : sh_state(other.sh_state.get()) { + if (sh_state) sh_state->inc-ref(); + } + + shared-wrapper& operator=(shared-wrapper&& other) noexcept = default; + shared-wrapper& operator=(const shared-wrapper& other) noexcept + requires same_as<Tag, split_t> { + return *this = shared-wrapper{other}; } };
@@ -6798,7 +6804,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. The member impls-for<shared-impl-tag>::get-state - is initialized with a callable object equal to the following lambda: + is initialized with a callable object equal to the following lambda + expression:
           []<class Sndr>(Sndr&& sndr, auto& rcvr) noexcept {
@@ -6839,28 +6846,34 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                 `old_head` will be equal to `state.sh_state`
                 when the child asynchronous operation has already completed.
 
-            - If `old_head` is equal to `state.sh_state`, calls
-                state.notify() and returns.
+            - Then, executes the following in a loop:
+
+                - If `old_head` is equal to `state.sh_state`, calls
+                    state.notify() and returns.
 
-            - Atomically does the following:
-                writes `old_head` into `state.next`, and
-                exchanges `state.sh_state->head` with `&state`.
-                This is typically done by executing
-                this step and the previous in an atomic compare-and-exchange
-                loop until the exchange succeeds.
+                - Otherwise, writes `old_head` into `state.next`,
+
+                - Atomically compares `state.sh_state->head` to `old_head`, and
+                    if they are equal, exchanges `state.sh_state->head`
+                    with `&state` and exits the loop. Otherwise, updates
+                    `old_head` with the new value of `state.sh_state->head`.
 
             - If `shared-impl-tag` is `split-impl-tag`, and
                 if `old_head` is equal to `nullptr`, calls
                 state.sh_state->start-op().
 
-10. If a sender returned from `ensure_started` is
-    destroyed without being connected to a receiver, or if it is connected but
-    the operation state is destroyed without having been started, or if stop has
-    been requested on the receiver's stop token prior to `start` having been
-    called, then when the child operation completes and it releases its shared
-    ownership of the `shared-state` object, the `shared-state`
-    object will be destroyed and the results of the child operation are
-    discarded.
+10. 
Under the following conditions, the results of the + child operation are discarded: + + - When a sender returned from `ensure_started` is destroyed without being + connected to a receiver, or + + - If the sender is connected to a receiver but the operation state + is destroyed without having been started, or + + - If polling the receiver's stop token indicates that stop has been + requested when `start` is called, and the operation has not yet + completed.
#### `execution::when_all` [exec.when.all] #### {#spec-execution.senders.adaptor.when_all} From 5f06d4587d5abfefaf5e1f4c0ec8b9cc64b8e5c5 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 16 Feb 2024 15:26:02 -0800 Subject: [PATCH 11/89] feedback from Lewis, and translate shared-wrapper spec into English --- execution.bs | 138 ++++++++++++++++++++++----------------------------- 1 file changed, 59 insertions(+), 79 deletions(-) diff --git a/execution.bs b/execution.bs index af0bb5c..1423cb0 100644 --- a/execution.bs +++ b/execution.bs @@ -6559,7 +6559,6 @@ template<class Domain, class Tag, sender Sndr, class... Args> virtual ~local-state-base() = default; virtual void notify() noexcept = 0; virtual void detach() noexcept = 0; - local-state-base* next{nullptr}; }; template<class Sndr, class Rcvr> @@ -6669,6 +6668,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> template<class Sndr> struct shared-state { using variant-type = see below; + using state-list-type = see below; + using state-flag-type = see below; explicit shared-state(Sndr&& sndr); @@ -6680,7 +6681,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> in_place_stop_source stop_src{}; variant-type result{}; - atomic<void*> head{nullptr}; + state-list-type waiting_states; + state-flag-type completed; atomic<size_t> ref_count{1}; connect_result_t<Sndr, shared-receiver<Sndr>> op_state; }; @@ -6697,46 +6699,54 @@ template<class Domain, class Tag, sender Sndr, class... Args> exception_ptr>, as-tuple<Sigs>...>, but with duplicate types removed. - 2.
+      2. Let `state-list-type` be a type that stores a list of pointers
+          to `local-state-base` objects and that permits atomic insertion.
+          Let `state-flag-type` be a type that can be atomically toggled
+          between `true` and `false`.
+
+      3. 
           explicit shared-state(Sndr&& sndr);
1. *Effects:* Initializes `op_state` with the result of connect(std::forward<Sndr>(sndr), shared-receiver{this}). - 3.
+          2. *Postcondition:* `waiting_states` is empty, and `completed` is `false`.
+
+      4. 
           void start-op() noexcept;
1. *Effects:* inc-ref(). If `stop_src.stop_requested()` is `true`, calls - notify(); otherwise, calls - `start(op_state)`. + notify(); otherwise, calls `start(op_state)`. - 4.
+      5. 
           void notify() noexcept;
- 1. *Effects:* Atomically exchanges the current value of `head` with - `this` and saves the previous value in a local variable `state` of - type local-state-base*. While `state` is not - `nullptr`, calls state->notify(), then sets - `state` to `state->next`. Finally, calls - dec-ref(). + 1. *Effects:* Atomically does the following: - 5.
+                - Sets `completed` to `true`, and
+
+                - Exchanges `waiting_states` with an empty list, storing the old
+                    value in a local `prior_states`. For each pointer `p` in
+                    `prior_states`, calls p->notify().
+                    Finally, calls dec-ref().
+
+      6. 
           void detach() noexcept;
- 1. *Effects:* Atomically reads the value of `head`. If it is `nullptr`, + 1. *Effects:* If `completed` is `false` and `waiting_states` is empty, calls `stop_src.request_stop()`. This has the effect of requesting early termination of any asynchronous operation that was started as a result of a call to `ensure_started`, but only if the resulting sender was never connected and started. - 5.
+      7. 
           void inc-ref() noexcept;
1. *Effects:* Increments `ref_count`. - 6.
+      8. 
           void dec-ref() noexcept;
1. *Effects:* Decrements `ref_count`. If the new value of @@ -6755,40 +6765,17 @@ template<class Domain, class Tag, sender Sndr, class... Args> return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
- where `shared-wrapper` is the exposition-only class template: - -
-      struct dec-ref { // exposition only
-        void operator()(auto* ptr) const noexcept { ptr->dec-ref(); }
-      };
-
-      template<class Sndr, class Tag>
-      struct shared-wrapper { // exposition only
-        unique_ptr<shared-state<Sndr>, dec-ref> sh_state; // exposition only
-
-        shared-wrapper(shared-state<Sndr>* ptr, Tag) noexcept : sh_state(ptr) {
-          if constexpr (same_as<Tag, ensure_started_t>)
-            sh_state->start-op();
-        }
-
-        ~shared-wrapper() {
-          if constexpr (same_as<Tag, ensure_started_t>)
-            if (sh_state) sh_state->detach();
-        }
-
-        shared-wrapper(shared-wrapper&&) noexcept = default;
-        shared-wrapper(const shared-wrapper& other) noexcept requires same_as<Tag, split_t>
-          : sh_state(other.sh_state.get()) {
-          if (sh_state) sh_state->inc-ref();
-        }
-
-        shared-wrapper& operator=(shared-wrapper&& other) noexcept = default;
-        shared-wrapper& operator=(const shared-wrapper& other) noexcept
-          requires same_as<Tag, split_t> {
-          return *this = shared-wrapper{other};
-        }
-      };
-      
+ where `shared-wrapper` is an exposition-only class that manages the + reference count of the `shared-state` object pointed to by `sh_state`. + `shared-wrapper` models `movable` with move operations nulling out the + moved-from object. If `tag` is `split_t`, `shared-wrapper` models + `copyable` with copy operations incrementing the reference count by calling + sh_state->inc-ref(). The constructor calls + sh_state->start-op() if `tag` is `ensure_started_t`. The + destructor has no effect if `sh_state` is null; otherwise, it calls + sh_state->detach() if `tag` is `ensure_started_t`; + and finally, it decrements the reference count by calling + sh_state->dec-ref(). 9. The exposition-only class template impls-for ([exec.snd.general]) is specialized for shared-impl-tag @@ -6824,42 +6811,35 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. *Effects:* - - Atomically reads the value of `state.sh_state->head` into a - local variable `old_head` of type `void*`. - - - If `old_head` is not equal to `state.sh_state`: + 1. If `state.sh_state->completed` is `true`, calls + state.notify() and returns. - - Calls: + 2. Otherwise, calls: -
-                    state.on_stop.emplace(
-                      get_stop_token(get_env(rcvr)),
-                      on-stop-request{state.sh_state->stop_src})
-                    
- - - If `shared-impl-tag` is - `ensure-started-impl-tag`, and if - `state.sh_state->stop_src.stop_requested()` - is `true`, calls `set_stopped(std::move(rcvr))` - and returns. +
+                state.on_stop.emplace(
+                  get_stop_token(get_env(rcvr)),
+                  on-stop-request{state.sh_state->stop_src})
+                
- `old_head` will be equal to `state.sh_state` - when the child asynchronous operation has already completed. + If `shared-impl-tag` is + `ensure-started-impl-tag`, and if + `state.sh_state->stop_src.stop_requested()` + is `true`, calls `set_stopped(std::move(rcvr))` + and returns. - - Then, executes the following in a loop: + 3. Then atomically does the following: - - If `old_head` is equal to `state.sh_state`, calls - state.notify() and returns. + - Inserts `&state` into `state.sh_state->waiting_states`, and - - Otherwise, writes `old_head` into `state.next`, + - Reads the value of `state.sh_state->completed`. - - Atomically compares `state.sh_state->head` to `old_head`, and - if they are equal, exchanges `state.sh_state->head` - with `&state` and exits the loop. Otherwise, updates - `old_head` with the new value of `state.sh_state->head`. + If the value is `true`, calls state.notify() + and returns. - - If `shared-impl-tag` is `split-impl-tag`, and - if `old_head` is equal to `nullptr`, calls + 4. If `shared-impl-tag` is `split-impl-tag`, and if + `&state` is the first item added to + `state.sh_state->waiting_states`, calls state.sh_state->start-op(). 10.
Under the following conditions, the results of the From cbe8e82834cfbfb824fe46be3015c55e57d903a5 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 16 Feb 2024 16:06:39 -0800 Subject: [PATCH 12/89] respecify `into_variant` with `basic-sender` --- execution.bs | 68 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 24 deletions(-) diff --git a/execution.bs b/execution.bs index c38ae18..e0ea292 100644 --- a/execution.bs +++ b/execution.bs @@ -7017,42 +7017,62 @@ template<class Domain, class Tag, sender Sndr, class... Args> value_types_of_t<Sndr, Env>;
-3. `into_variant` is a customization point object. For some subexpression `sndr`, - let `Sndr` be `decltype((sndr))`. If `Sndr` does not satisfy `sender`, - `into_variant(sndr)` is ill-formed. Otherwise, `into_variant(sndr)` is - expression-equivalent to: +3. The name `into_variant` denotes a customization point object. For a + subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If `Sndr` does not + satisfy `sender`, `into_variant(sndr)` is ill-formed. + +4. Otherwise, the expression `into_variant(sndr)` is expression-equivalent to:
       transform_sender(
         get-domain-early(sndr),
-        make-into-variant-sender(sndr))
+        make-sender(into_variant, {}, sndr))
       
- where make-into-variant-sender(sndr) is - expression-equivalent to make-sender(into_variant, - {}, sndr) and returns a sender object `sndr2` that behaves - as follows: - - 1. When `sndr2` is connected with some receiver `out_rcvr`, it: +5. The exposition-only class template `impls-for` ([exec.snd.general]) is + specialized for `into_variant` as follows: - 1. Constructs a receiver `rcvr` such that: +
+    template<>
+    struct impls-for<into_variant_t> : default-impls {
+      static constexpr auto get-state = see below;
+      static constexpr auto complete = see below;
+    };
+    
- 1. If `set_value(rcvr, ts...)` is called, calls set_value(out_rcvr, - into-variant-type<Sndr, - env_of_t<decltype((rcvr))>>(decayed-tuple<decltype(ts)...>(ts...))). - If this expression throws an exception, calls `set_error(out_rcvr, - current_exception())`. + 1. The member + impls-for<into_variant_t>::get-state is + initialized with a callable object equal to the following lambda: - 2. `set_error(rcvr, err)` is expression-equivalent to `set_error(out_rcvr, - err)`. +
+          []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept
+            -> type_identity<into-variant-type<child-type<Sndr>, env_of_t<Rcvr>>> {
+            return {};
+          }
+          
- 3. `set_stopped(rcvr)` is expression-equivalent to - `set_stopped(out_rcvr)`. + 2. The member impls-for<into_variant_t>::complete + is initialized with a callable object equal to the following lambda: - 2. Calls `connect(sndr, rcvr)`, resulting in an operation state `op_state2`. +
+          []<class State, class Rcvr, class Tag, class... Args>(
+              auto, State, Rcvr& rcvr, Tag, Args&&... args) noexcept {
+            if constexpr (same_as<Tag, set_value_t>) {
+              using variant_type = typename State::type;
+              using tuple_type = decayed-tuple<Args...>;
+              try {
+                set_value(std::move(rcvr),
+                          variant_type(tuple_type(std::forward<Args>(args)...)));
+              }
+              catch (...) {
+                set_error(std::move(rcvr), current_exception());
+              }
+            } else {
+              Tag()(std::move(rcvr), std::forward<Args>(args)...);
+            }
+          }
+          
- 3. Returns an operation state `op_state` that contains `op_state2`. When - `start(op_state)` is called, calls `start(op_state2)`. #### `execution::stopped_as_optional` [exec.stopped.as.optional] #### {#spec-execution.senders.adapt.stopped_as_optional} From 9d4181ca20751a3f066d421a155d1e8c360dfbbb Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sat, 27 Jan 2024 15:04:39 -0800 Subject: [PATCH 13/89] respecify `when_all` and `when_all_with_variant` using `basic-sender` --- execution.bs | 321 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 222 insertions(+), 99 deletions(-) diff --git a/execution.bs b/execution.bs index c38ae18..54f902c 100644 --- a/execution.bs +++ b/execution.bs @@ -6853,8 +6853,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> a sender that completes when all input senders have completed. `when_all` only accepts senders with a single value completion signature and on success concatenates all the input senders' value result datums into its own value - completion operation. `when_all_with_variant(sndr...)` is semantically - equivalent to `when_all(into_variant(sndr)...)`, where `sndr` is a pack of + completion operation. `when_all_with_variant(sndrs...)` is semantically + equivalent to `when_all(into_variant(sndrs)...)`, where `sndrs` is a pack of subexpressions of sender types. 2. The names `when_all` and `when_all_with_variant` denote customization point @@ -6865,122 +6865,252 @@ template<class Domain, class Tag, sender Sndr, class... Args> when_all_with_variant(sndri...) are ill-formed if any of the following is true: - * If the number of subexpressions sndri... is 0, or + * If the number of subexpressions in sndri... is 0, or * If any type Sndri does not satisfy `sender`. - * If the expression get-domain-early(sndri) has a - different type for any other value of i. + * If the types of the expressions + get-domain-early(sndri) do not share + a common type ([meta.trans.other]) for all values of i. - Otherwise, those expressions have the semantics specified below. + Otherwise, let `CD` be the common type of the input senders' domains. 3. The expression when_all(sndri...) is expression-equivalent to:
       transform_sender(
-        get-domain-early(sndr0),
-        make-when-all-sender(sndr0, ... sndrn-1));
+        CD(),
+        make-sender(when_all, {}, sndr0, ... sndrn-1));
       
- where make-when-all-sender(sndri...) is - expression-equivalent to make-sender(when_all, - {}, sndri...) and returns a sender - object `w` of type `W` that behaves as follows: - - 1. When `w` is connected with some receiver `out_rcvr` of type `OutRcvr`, it - returns an operation state `op_state` specified as below: - - 1. For each sender sndri, constructs a - receiver rcvri such that: - - 1. If set_value(rcvri, - ti...) is called for every - rcvri, `op_state`'s associated stop - callback optional is reset and set_value(out_rcvr, - t0..., t1..., ..., - tn-1...) is called, where `n` the number - of subexpressions in sndri.... - - 2. Otherwise, `set_error` or `set_stopped` was called for at least - one receiver rcvri. If the first such - to complete did so with the call - set_error(rcvri, err), `request_stop` - is called on `op_state`'s associated stop source. When all child - operations have completed, `op_state`'s associated stop callback - optional is reset and `set_error(out_rcvr, err)` is called. - - 3. Otherwise, `request_stop` is called on `op_state`'s associated - stop source. When all child operations have completed, - `op_state`'s associated stop callback optional is reset and - `set_stopped(out_rcvr)` is called. - - 4. For each receiver rcvri, - get_env(rcvri) is an expression - env such that - get_stop_token(env) is well-formed and returns - the results of calling `get_token()` on `op_state`'s associated - stop source, and for which tag_invoke(tag, env, - args...) is expression-equivalent to `tag(get_env(out_rcvr), - args...)` for all arguments `args...` and all `tag` whose type - satisfies forwarding-query and is not - `get_stop_token_t`. - - 2. For each sender sndri, calls - connect(sndri, rcvri), - resulting in operation states - child_opi. - - 3. Returns an operation state `op_state` that contains: - - * Each operation state child_opi, - - * A stop source of type `in_place_stop_source`, - - * A stop callback of type - optional<stop_token_of_t<env_of_t<OutRcvr>>::callback_type<stop-callback-fn>>, - where stop-callback-fn is the unspecified - class type: +9. The exposition-only class template impls-for + ([exec.snd.general]) is specialized for `when_all_t` as follows: -
-                struct stop-callback-fn {
-                  in_place_stop_source& stop_src_;
-                  void operator()() noexcept {
-                    stop_src_.request_stop();
+        
+        template<>
+        struct impls-for<when_all_t> : default-impls {
+          static constexpr auto get-attrs = see below;
+          static constexpr auto get-env = see below;
+          static constexpr auto get-state = see below;
+          static constexpr auto start = see below;
+          static constexpr auto complete = see below;
+        };
+        
+ + 1. The member impls-for<when_all_t>::get-attrs + is initialized with a callable object equal to the following lambda + expression: + +
+          [](auto&&, auto&&... child) noexcept {
+            auto domain_fn = []<class... Ds>(Ds...) noexcept { return common_type_t<Ds...>(); };
+            using domain_type = decltype(domain_fn(get-domain-early(child)...));
+            if constexpr (same_as<domain_type, default_domain>) {
+              return empty_env();
+            } else {
+              return MAKE-ENV(get_domain, domain_type());
+            }
+          }
+          
+ + 2. The member impls-for<when_all_t>::get-env + is initialized with a callable object equal to the following lambda + expression: + +
+          []<class State, class Rcvr>(auto&&, State& state, const Receiver& rcvr) noexcept {
+            return JOIN-ENV(
+              MAKE-ENV(get_stop_token, state.stop_src.get_token()), get_env(rcvr));
+          }
+          
+ + 3. The member impls-for<when_all_t>::get-state + is initialized with a callable object equal to the following lambda + expression: + +
+          
BUG: `apply` isn't constrained
+ []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) + -> decltype(apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr))) { + return apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr)); + } +
+ + where `make-state` is the following exposition-only class type: + +
+          template<class Sndr, class Env>
+          concept max-1-sender-in = sender_in<Sndr, Env> &&
+            (tuple_size_v<value_types_of_t<Sndr, Env, tuple, tuple>> <= 1);
+
+          enum class disposition { started, error, stopped };
+
+          template <class Rcvr>
+          struct make-state {
+            const env_of_t<Rcvr>& env;
+
+            template <max-1-sender-in<env_of_t<Rcvr>>... Sndrs>
+            auto operator()(auto, auto, Sndrs&&... sndrs) const {
+              using values_tuple = see below;
+              using errors_variant = see below;
+              using stop_token = stop_token_of_t<env_of_t<Rcvr>>;
+              using stop_callback = stop_token::template callback_type<on-stop-request>;
+
+              struct state {
+                void arrive(Rcvr& rcvr) noexcept {
+                  if (0 == --count) {
+                    complete(rcvr);
                   }
-                };
-                
+ } + + void complete(Rcvr& rcvr) noexcept; // see below + + atomic<size_t> count{sizeof...(sndrs)}; + in_place_stop_source stop_src{}; + atomic<disposition> disp{disposition::started}; + errors_variant errors{}; + values_tuple values{}; + optional<stop_callback> on_stop{nullopt}; + }; + + return state{}; + } + }; +
- 4. When `start(op_state)` is called it: + 1. Let copy-fail be `exception_ptr` if decay-copying any of the + input senders' result datums can potentially throw; otherwise, + `none-such`, where `none-such` is an unspecified + empty class type. - * Emplace constructs the stop callback optional with the arguments - `get_stop_token(get_env(out_rcvr))` and - stop-callback-fn{stop-src}, where - stop-src refers to the stop source of - `op_state`. + 2. The alias `values_tuple` denotes the type + tuple<value_types_of_t<Sndrs, env_of_t<Rcvr>, + decayed-tuple, optional>...> if that type is well-formed; + otherwise, `tuple<>`. - * Then, it checks to see if - stop-src.stop_requested() is true. If so, it - calls `set_stopped(out_rcvr)`. + 3. Let `errors_variant` denotes the type + variant<none-such, copy-fail, + Es...> with duplicate types removed, where + Es is the pack of the decayed types of all the + input senders' possible error result datums. - * Otherwise, calls start(child_opi) - for each child_opi. + 4. The member void state::complete(Rcvr& rcvr) + noexcept behaves as follows: -4. The expression when_all_with_variant(sndri...) is + 1. If `disp` is equal to disposition::started, + calls: + +
+                  auto tie = []<class... T>(tuple<T...>& t) noexcept { return tuple<T&...>(t); };
+                  auto set = [&](auto&... t) noexcept { set_value(std::move(rcvr), std::move(t)...); };
+                  apply(
+                    [&](auto&... opts) noexcept {
+                      if constexpr (sizeof...(opts) != 0)
+                        apply(set, tuple_cat(tie(*opts)...));
+                    },
+                    values);
+                  
+ + 2. Otherwise, if `disp` is equal to + disposition::error, calls: + +
+                  visit(
+                    [&]<class Error>(Error& error) noexcept {
+                      if constexpr (!same_as<Error, none-such>) {
+                        set_error(std::move(rcvr), std::move(error));
+                      }
+                    },
+                    errors);
+                  
+ + 3. Otherwise, calls `set_stopped(std::move(rcvr))`. + + 4. The member impls-for<when_all_t>::start + is initialized with a callable object equal to the following lambda + expression: + +
+          []<class State, class Rcvr, class... Ops>(
+              State& state, Rcvr& rcvr, Ops&... ops) noexcept -> void {
+            state.on_stop.emplace(
+              get_stop_token(get_env(rcvr)),
+              on-stop-request{state.stop_src});
+            if (state.stop_src.stop_requested()) {
+              set_stopped(std::move(rcvr));
+            } else {
+              (start(ops), ...);
+            }
+          }
+          
+ + 4. The member impls-for<when_all_t>::complete + is initialized with a callable object equal to the following lambda + expression: + +
+          []<class Index, class State, class Rcvr, class Set, class... Args>(
+              this auto& complete, Index, State& state, Rcvr& rcvr, Set, Args&&... args) noexcept -> void {
+            if constexpr (same_as<Set, set_error_t>) {
+              if (disposition::error != state.disp.exchange(disposition::error)) {
+                state.stop_src.request_stop();
+                TRY-EMPLACE-ERROR(state.errors, std::forward<Args>(args)...);
+              }
+            } else if constexpr (same_as<Set, set_stopped_t>) {
+              auto expected = disposition::started;
+              if (state.disp.compare_exchange_strong(expected, disposition::stopped)) {
+                state.stop_src.request_stop();
+              }
+            } else if constexpr (!same_as<decltype(State::values), tuple<>>) {
+              if (state.disp == disposition::started) {
+                auto& opt = get<Index::value>(state.values);
+                TRY-EMPLACE-VALUE(complete, opt, std::forward<Args>(args)...);
+              }
+            }
+
+            state.arrive(rcvr);
+          }
+          
+ + where for subexpressions `v` and `e`, TRY-EMPLACE-ERROR(v, + e) is equivalent to: + +
+          try {
+            v.template emplace<decltype(auto(e))>(e);
+          } catch (...) {
+            v.template emplace<exception_ptr>(current_exception());
+          }
+          
+ + if the expression `decltype(auto(e))(e)` is potentially throwing; otherwise, + `v.template emplace(e)`; and where for subexpressions + `c`, `o`, and pack of subexpressions `as`, TRY-EMPLACE-VALUE(c, + o, as...) is equivalent to: + +
+          try {
+            o.emplace(as...);
+          } catch (...) {
+            c(Index(), state, rcvr, set_error, current_exception());
+            return;
+          }
+          
+ + if the expression decayed-tuple<decltype(as)...>{as...} + is potentially throwing; otherwise, `o.emplace(as...)`. + +5. The expression when_all_with_variant(sndri...) is expression-equivalent to:
       transform_sender(
-        get-domain-early(sndr0),
+        CD(),
         make-sender(when_all_with_variant, {}, sndr0, ... sndrn-1));
       
- where make-when-all-sender(sndri...) is - expression-equivalent to make-sender(when_all, - {}, sndri...) and returns a sender - object `w` of type `W` that behaves as follows: - -5. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If +6. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If sender-for<Sndr, when_all_with_variant_t> is `false`, then the expression `when_all_with_variant.transform_sender(sndr, env)` is ill-formed; otherwise, it is equal to: @@ -6995,13 +7125,6 @@ template<class Domain, class Tag, sender Sndr, class... Args> receiver with an execution domain that does not customize `when_all_with_variant`. -4. Given a pack of subexpressions `sndr...`, let `out_sndr` be an object returned from - `when_all(sndr...)` or `when_all_with_variant(sndr...)` or a copy of such, and let - `env` be the environment object returned from `get_env(out_sndr)`. Given a query - object `q`, `tag_invoke(q, env)` is expression-equivalent to - get-domain-early(sndr0) when `q` is - `get_domain`; otherwise, it is ill-formed. - #### `execution::into_variant` [exec.into.variant] #### {#spec-execution.senders.adapt.into_variant} 1. `into_variant` adapts a sender with multiple value completion signatures into From 4084306b06187815cbc829b5e399b4340752aa94 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sun, 18 Feb 2024 10:47:29 -0800 Subject: [PATCH 14/89] update R8 release notes --- execution.bs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/execution.bs b/execution.bs index 060137a..08218a2 100644 --- a/execution.bs +++ b/execution.bs @@ -1148,6 +1148,10 @@ The changes since R7 are as follows: * The `sender_in` concept requires that `E` satisfies `queryable`. + * Senders of more than one value are now `co_await`-able in coroutines, the + result of which is a `std::tuple` of the values (which is suitable as the + initializer of a structured binding). + Enhancements: * The exposition-only class template basic-sender is greatly From 1a6684d6c194b6167a461d4089e7922ca7a41427 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sun, 18 Feb 2024 10:56:20 -0800 Subject: [PATCH 15/89] fix typo --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 08218a2..a8614d2 100644 --- a/execution.bs +++ b/execution.bs @@ -7010,7 +7010,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> decayed-tuple, optional>...> if that type is well-formed; otherwise, `tuple<>`. - 3. Let `errors_variant` denotes the type + 3. The alias `errors_variant` denotes the type variant<none-such, copy-fail, Es...> with duplicate types removed, where Es is the pack of the decayed types of all the From 6d97e0c4753a56f0b62270528a7e9626bec024cd Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 20 Feb 2024 22:02:22 -0800 Subject: [PATCH 16/89] assorted minor fixes --- execution.bs | 38 ++++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/execution.bs b/execution.bs index a8614d2..3337ab7 100644 --- a/execution.bs +++ b/execution.bs @@ -336,7 +336,7 @@ struct recv_op : operation_base { friend void tag_invoke(std::execution::start_t, recv_op& self) noexcept { // Avoid even calling WSARecv() if operation already cancelled auto st = std::execution::get_stop_token( - std::get_env(self.receiver)); + std::execution::get_env(self.receiver)); if (st.stop_requested()) { std::execution::set_stopped(std::move(self.receiver)); return; @@ -1136,6 +1136,9 @@ The changes since R7 are as follows: * `get_env(obj)` is required to be nothrow. + * `get_env` and the associated environment utilities are moved back into + `std::execution` from `std::`. + * `make_completion_signatures` is renamed `transform_completion_signatures_of` and is expressed in terms of the new `transform_completion_signatures`, which takes an input set of completion signatures instead of a sender and an @@ -1931,7 +1934,7 @@ This CPO takes a single parameter, which is the execution environment of the rec that the operation can use to check for stop-requests for that operation. As the caller of `execution::connect` typically has control over the receiver -type it passes, it is able to customise the `std::get_env()` CPO for that +type it passes, it is able to customise the `std::execution::get_env()` CPO for that receiver to return an execution environment that hooks the `execution::get_stop_token()` CPO to return a stop-token that the receiver has control over and that it can use to communicate a stop-request to the operation @@ -3287,7 +3290,7 @@ using tag-invoke::tag_invoke_result_t; using tag-invoke::tag_invoke_result; template<auto& Tag> - using tag_t = decay_t<decltype(Tag)>; + using tag_t = decltype(auto(Tag));
@@ -4118,17 +4121,6 @@ namespace std { template<class T> concept forwarding-query = // exposition only forwarding_query(T{}); - - namespace exec-envs { // exposition only - struct empty_env {}; - struct get_env_t; - } - using envs-envs::empty_env; - using envs-envs::get_env_t; - inline constexpr get_env_t get_env {}; - - template<class T> - using env_of_t = decltype(get_env(declval<T>())); } namespace std::execution { @@ -4154,11 +4146,22 @@ namespace std::execution { template<class CPO> inline constexpr get_completion_scheduler_t<CPO> get_completion_scheduler{}; + namespace exec-envs { // exposition only + struct empty_env {}; + struct get_env_t; + } + using envs-envs::empty_env; + using envs-envs::get_env_t; + inline constexpr get_env_t get_env {}; + + template<class T> + using env_of_t = decltype(get_env(declval<T>())); + // [exec.domain.default], execution domains struct default_domain; // [exec.sched], schedulers - template<class Sndr> + template<class Sch> concept scheduler = see below; // [exec.recv], receivers @@ -4663,7 +4666,7 @@ enum class forward_progress_guarantee { `set_error_t`, or `set_stopped_t`, `get_completion_scheduler(q)` is ill-formed. Otherwise, `get_completion_scheduler(q)` is expression-equivalent to mandate-nothrow-call(tag_invoke, - get_completion_scheduler, as_const(q)) if this expression is + get_completion_scheduler<Tag>, as_const(q)) if this expression is well-formed. * Mandates: The type of the expression above satisfies @@ -5718,8 +5721,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> coroutine_handle<connect-awaitable-promise>::from_promise(*this)}; } - friend auto tag_invoke(get_env_t, connect-awaitable-promise& self) - noexcept(nothrow-callable<get_env_t, const DR&>) -> env_of_t<const DR&> { + friend env_of_t<const DR&> tag_invoke(get_env_t, const connect-awaitable-promise& self) noexcept { return get_env(self.rcvr); } }; From 748a25443d8f0a20d221cef4252ed508e0248911 Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 22 Feb 2024 10:42:28 +1030 Subject: [PATCH 17/89] Fix typo in numbering of section 4 of exec.when.all --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 3337ab7..0677789 100644 --- a/execution.bs +++ b/execution.bs @@ -6907,7 +6907,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(when_all, {}, sndr0, ... sndrn-1));
-9. The exposition-only class template impls-for +4. The exposition-only class template impls-for ([exec.snd.general]) is specialized for `when_all_t` as follows:

From 777c8ce54f210109ebd2e1be6e57c1f66a42b455 Mon Sep 17 00:00:00 2001
From: Lewis Baker 
Date: Thu, 22 Feb 2024 10:48:42 +1030
Subject: [PATCH 18/89] Use "... with a callable object equivalent to the
 following lambda" instead of "... with a callable object equal to the
 following lambda".

As suggested during LWG review 2024-02-21
---
 execution.bs | 38 +++++++++++++++++++-------------------
 1 file changed, 19 insertions(+), 19 deletions(-)

diff --git a/execution.bs b/execution.bs
index 0677789..5869479 100644
--- a/execution.bs
+++ b/execution.bs
@@ -5237,7 +5237,7 @@ enum class forward_progress_guarantee {
             [dcl.struct.bind].
 
         5. The member default-impls::get-attrs is initialized
-            with a callable object equal to the following lambda:
+            with a callable object equivalent to the following lambda:
 
               
               [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
@@ -5249,7 +5249,7 @@ enum class forward_progress_guarantee {
               
6. The member default-impls::get-env is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
               []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept
@@ -5259,7 +5259,7 @@ enum class forward_progress_guarantee {
               
7. The member default-impls::get-state is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
               []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept -> decltype(auto) {
@@ -5268,7 +5268,7 @@ enum class forward_progress_guarantee {
               
8. The member default-impls::start is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
               [](auto& state, auto& rcvr, auto&... ops) noexcept -> void {
@@ -5277,7 +5277,7 @@ enum class forward_progress_guarantee {
               
9. The member default-impls::complete is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
               []<class Index, class Rcvr, class Tag, class... Args>(
@@ -6145,7 +6145,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         
1. The member impls-for<schedule_from_t>::get-attrs is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
           [](const auto& data, const auto& child) noexcept -> decltype(auto) {
@@ -6154,7 +6154,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
2. The member impls-for<schedule_from_t>::get-state is initialized - with a callable object equal to the following lambda: + with a callable object equivalent to the following lambda:
           []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
@@ -6215,7 +6215,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                 
3. The member impls-for<schedule_from_t>::complete - is initialized with a callable object equal to the following lambda: + is initialized with a callable object equivalent to the following lambda:
           []<class Tag, class... Args>(auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
@@ -6370,7 +6370,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
             
2. impls-for<tag_t<let-cpo>>::get-state is - is initialized with a callable object equal to the following: + is initialized with a callable object equivalent to the following:
             []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) requires see below {
@@ -6425,7 +6425,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
             
4. impls-for<tag_t<let-cpo>>::complete is - is initialized with a callable object equal to the following: + is initialized with a callable object equivalent to the following:
             []<class Tag, class... Args>
@@ -6490,7 +6490,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         
1. The member impls-for<bulk_t>::complete is - initialized with a callable object equal to the following lambda: + initialized with a callable object equivalent to the following lambda:
           []<class Index, class State, class Rcvr, class Tag, class... Args>
@@ -6806,7 +6806,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     1. The member
         impls-for<shared-impl-tag>::get-state
-        is initialized with a callable object equal to the following lambda
+        is initialized with a callable object equivalent to the following lambda
         expression:
 
           
@@ -6922,7 +6922,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         
1. The member impls-for<when_all_t>::get-attrs - is initialized with a callable object equal to the following lambda + is initialized with a callable object equivalent to the following lambda expression:
@@ -6938,7 +6938,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
2. The member impls-for<when_all_t>::get-env - is initialized with a callable object equal to the following lambda + is initialized with a callable object equivalent to the following lambda expression:
@@ -6949,7 +6949,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
3. The member impls-for<when_all_t>::get-state - is initialized with a callable object equal to the following lambda + is initialized with a callable object equivalent to the following lambda expression:
@@ -7051,7 +7051,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
               3. Otherwise, calls `set_stopped(std::move(rcvr))`.
 
     4. The member impls-for<when_all_t>::start
-        is initialized with a callable object equal to the following lambda
+        is initialized with a callable object equivalent to the following lambda
         expression:
 
           
@@ -7069,7 +7069,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
4. The member impls-for<when_all_t>::complete - is initialized with a callable object equal to the following lambda + is initialized with a callable object equivalent to the following lambda expression:
@@ -7188,7 +7188,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     1. The member
         impls-for<into_variant_t>::get-state is
-        initialized with a callable object equal to the following lambda:
+        initialized with a callable object equivalent to the following lambda:
 
           
           []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept
@@ -7198,7 +7198,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
2. The member impls-for<into_variant_t>::complete - is initialized with a callable object equal to the following lambda: + is initialized with a callable object equivalent to the following lambda:
           []<class State, class Rcvr, class Tag, class... Args>(

From b12c74dae7663cd8af254b2fbae9d15759b6dbef Mon Sep 17 00:00:00 2001
From: Lewis Baker 
Date: Thu, 22 Feb 2024 10:58:47 +1030
Subject: [PATCH 19/89] Use "evaluates" instead of "calls" in description of
 [exec.when.all] state::complete effects.

The  code blocks below are not functions and so cannot be "called".
---
 execution.bs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/execution.bs b/execution.bs
index 5869479..b052947 100644
--- a/execution.bs
+++ b/execution.bs
@@ -7022,7 +7022,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
               noexcept behaves as follows:
 
               1. If `disp` is equal to disposition::started,
-                  calls:
+                  evaluates:
 
                   
                   auto tie = []<class... T>(tuple<T...>& t) noexcept { return tuple<T&...>(t); };
@@ -7036,7 +7036,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                   
2. Otherwise, if `disp` is equal to - disposition::error, calls: + disposition::error, evaluates:
                   visit(
@@ -7048,7 +7048,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                     errors);
                   
- 3. Otherwise, calls `set_stopped(std::move(rcvr))`. + 3. Otherwise, evaluates `set_stopped(std::move(rcvr))`. 4. The member impls-for<when_all_t>::start is initialized with a callable object equivalent to the following lambda From 3d1ede61e2c6488c687a4bff4946fbdf87158872 Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 22 Feb 2024 11:01:43 +1030 Subject: [PATCH 20/89] Remove `if constexpr` from [exec.when.all] state::complete handling of `disposition::started` case. The if constexpr was guarding against the case where there is a zero-sized pack of optionals holding the values, however p2 already says that when_all is ill-formed if the number of child senders is zero. --- execution.bs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index b052947..9ad0339 100644 --- a/execution.bs +++ b/execution.bs @@ -7029,8 +7029,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> auto set = [&](auto&... t) noexcept { set_value(std::move(rcvr), std::move(t)...); }; apply( [&](auto&... opts) noexcept { - if constexpr (sizeof...(opts) != 0) - apply(set, tuple_cat(tie(*opts)...)); + apply(set, tuple_cat(tie(*opts)...)); }, values);
From 2ac9f0e57bde748e6aa6409edc266a06b4f4dbe6 Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 22 Feb 2024 11:29:03 +1030 Subject: [PATCH 21/89] Explicitly reset the on_stop stop-callback object before calling completion function in [exec.when.all] stae::complete effects. It was considered too subtle to be relying on the destruction order of the members declared in the exposition-only local `state` struct to guarantee that the stop-callback is destroyed before the stop-source which the execution of the stop-callback might access. It also wasn't clear whether the listed order of member declarations in the 'state' structure was considered normative or whether we wanted to give implementations flexibility to declare members in different orders. The alternative considered was to add a note, or possibly something normative that requires that the 'on_stop' member is declared after the 'stop_src' member so that during destruction of the operation-state the stop-callback is destroyed before the stop-source. --- execution.bs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 9ad0339..5939b1c 100644 --- a/execution.bs +++ b/execution.bs @@ -7027,6 +7027,8 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                   auto tie = []<class... T>(tuple<T...>& t) noexcept { return tuple<T&...>(t); };
                   auto set = [&](auto&... t) noexcept { set_value(std::move(rcvr), std::move(t)...); };
+
+                  on_stop.reset();
                   apply(
                     [&](auto&... opts) noexcept {
                       apply(set, tuple_cat(tie(*opts)...));
@@ -7038,6 +7040,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                   disposition::error, evaluates:
 
                   
+                  on_stop.reset();
                   visit(
                     [&]<class Error>(Error& error) noexcept {
                       if constexpr (!same_as<Error, none-such>) {
@@ -7047,7 +7050,12 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                     errors);
                   
- 3. Otherwise, evaluates `set_stopped(std::move(rcvr))`. + 3. Otherwise, evaluates: + +
+                on_stop.reset();
+                set_stopped(std::move(rcvr));
+                
4. The member impls-for<when_all_t>::start is initialized with a callable object equivalent to the following lambda @@ -7060,6 +7068,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> get_stop_token(get_env(rcvr)), on-stop-request{state.stop_src}); if (state.stop_src.stop_requested()) { + state.on_stop.reset(); set_stopped(std::move(rcvr)); } else { (start(ops), ...); From 947473d2c714cad073bdce5dd16c3b6b3abbdf56 Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 22 Feb 2024 11:30:04 +1030 Subject: [PATCH 22/89] Fix duplicate numbering of paragraph describing impls-for::complete. Paragraph number 4 was duplicated. Changed to 5. --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 5939b1c..a3d8b58 100644 --- a/execution.bs +++ b/execution.bs @@ -7076,7 +7076,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> }
- 4. The member impls-for<when_all_t>::complete + 5. The member impls-for<when_all_t>::complete is initialized with a callable object equivalent to the following lambda expression: From 267ca4fb0cf98ba44152aa2c4f6aa9311b02fd26 Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 22 Feb 2024 13:43:34 +1030 Subject: [PATCH 23/89] Massaged phrasing of TRY-EMPLACE-ERROR and TRY-EMPLACE-VALUE. The "where for subexpressions" phrasing seemed grammatically weird. --- execution.bs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/execution.bs b/execution.bs index a3d8b58..9a99a50 100644 --- a/execution.bs +++ b/execution.bs @@ -7104,8 +7104,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> }
- where for subexpressions `v` and `e`, TRY-EMPLACE-ERROR(v, - e) is equivalent to: + where TRY-EMPLACE-ERROR(v, e), for subexpressions `v` and `e`, is equivalent to:
           try {
@@ -7116,9 +7115,8 @@ template<class Domain, class Tag, sender Sndr, class... Args>
           
if the expression `decltype(auto(e))(e)` is potentially throwing; otherwise, - `v.template emplace(e)`; and where for subexpressions - `c`, `o`, and pack of subexpressions `as`, TRY-EMPLACE-VALUE(c, - o, as...) is equivalent to: + `v.template emplace(e)`; and where TRY-EMPLACE-VALUE(c, + o, as...), for subexpressions `c`, `o`, and pack of subexpressions `as`, is equivalent to:
           try {

From a9e77cb72dff99e0979718bc098b3490b4f5880e Mon Sep 17 00:00:00 2001
From: Lewis Baker 
Date: Thu, 22 Feb 2024 13:47:29 +1030
Subject: [PATCH 24/89] Rephrase wording for
 when_all_with_variant.transform_sender(sndr, env).

- "Let x be subexpressions, such that X is decltype((x))" replaced with "Given subexpressions x ..." and then just use decltype(x) in-place in the one place it was used instead of defining another term for that.
- Refer to the code-block below as "the body of the `transform_sender` member-function" instead of saying the call expression "is equal to" the the code-block.
---
 execution.bs | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/execution.bs b/execution.bs
index 9a99a50..ba8095d 100644
--- a/execution.bs
+++ b/execution.bs
@@ -7139,14 +7139,14 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         make-sender(when_all_with_variant, {}, sndr0, ... sndrn-1));
       
-6. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If - sender-for<Sndr, when_all_with_variant_t> is `false`, +6. Given subexpressions `sndr` and `env`, if + sender-for<decltype((sndr)), when_all_with_variant_t> is `false`, then the expression `when_all_with_variant.transform_sender(sndr, env)` is - ill-formed; otherwise, it is equal to: + ill-formed; otherwise, the body of the `transform_sender` member-function is equivalent to:
-      auto [tag, data, ...child] = sndr;
-      return when_all(into_variant(std::move(child))...);
+        auto [tag, data, ...child] = sndr;
+        return when_all(into_variant(std::move(child))...);
       
This causes the `when_all_with_variant(sndr...)` sender From 6310cf93eef3287fffdb136abaa717cb0c66db8b Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 22 Feb 2024 13:06:40 -0800 Subject: [PATCH 25/89] P2300R8 --- P2300R8.html | 10229 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 10229 insertions(+) create mode 100644 P2300R8.html diff --git a/P2300R8.html b/P2300R8.html new file mode 100644 index 0000000..80db2c3 --- /dev/null +++ b/P2300R8.html @@ -0,0 +1,10229 @@ + + + + + P2300R8: `std::execution` + + + + + + + + + + + + + + + + + +
+

+

P2300R8
std::execution

+

Published Proposal,

+
+
+
Authors: +
+
+
+
+
+
+
+
+
+
Source: +
GitHub +
Issue Tracking: +
GitHub +
Project: +
ISO/IEC JTC1/SC22/WG21 14882: Programming Language — C++ +
Audience: +
SG1, LEWG +
+
+
+
+
+ +
+

1. Introduction

+

This paper proposes a self-contained design for a Standard C++ framework for managing asynchronous execution on generic execution resources. It is based on the ideas in A Unified Executors Proposal for C++ and its companion papers.

+

1.1. Motivation

+

Today, C++ software is increasingly asynchronous and parallel, a trend that is likely to only continue going forward. +Asynchrony and parallelism appears everywhere, from processor hardware interfaces, to networking, to file I/O, to GUIs, to accelerators. +Every C++ domain and every platform needs to deal with asynchrony and parallelism, from scientific computing to video games to financial services, from the smallest mobile devices to your laptop to GPUs in the world’s fastest supercomputer.

+

While the C++ Standard Library has a rich set of concurrency primitives (std::atomic, std::mutex, std::counting_semaphore, etc) and lower level building blocks (std::thread, etc), we lack a Standard vocabulary and framework for asynchrony and parallelism that C++ programmers desperately need. std::async/std::future/std::promise, C++11’s intended exposure for asynchrony, is inefficient, hard to use correctly, and severely lacking in genericity, making it unusable in many contexts. +We introduced parallel algorithms to the C++ Standard Library in C++17, and while they are an excellent start, they are all inherently synchronous and not composable.

+

This paper proposes a Standard C++ model for asynchrony, based around three key abstractions: schedulers, senders, and receivers, and a set of customizable asynchronous algorithms.

+

1.2. Priorities

+
    +
  • +

    Be composable and generic, allowing users to write code that can be used with many different types of execution resources.

    +
  • +

    Encapsulate common asynchronous patterns in customizable and reusable algorithms, so users don’t have to invent things themselves.

    +
  • +

    Make it easy to be correct by construction.

    +
  • +

    Support the diversity of execution resources and execution agents, because not all execution agents are created equal; some are less capable than others, but not less important.

    +
  • +

    Allow everything to be customized by an execution resource, including transfer to other execution resources, but don’t require that execution resources customize everything.

    +
  • +

    Care about all reasonable use cases, domains and platforms.

    +
  • +

    Errors must be propagated, but error handling must not present a burden.

    +
  • +

    Support cancellation, which is not an error.

    +
  • +

    Have clear and concise answers for where things execute.

    +
  • +

    Be able to manage and terminate the lifetimes of objects asynchronously.

    +
+

1.3. Examples: End User

+

In this section we demonstrate the end-user experience of asynchronous programming directly with the sender algorithms presented in this paper. See § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers for short explanations of the algorithms used in these code examples.

+

1.3.1. Hello world

+
using namespace std::execution;
+
+scheduler auto sch = thread_pool.scheduler();                                 // 1
+
+sender auto begin = schedule(sch);                                            // 2
+sender auto hi = then(begin, []{                                              // 3
+    std::cout << "Hello world! Have an int.";                                 // 3
+    return 13;                                                                // 3
+});                                                                           // 3
+sender auto add_42 = then(hi, [](int arg) { return arg + 42; });              // 4
+
+auto [i] = this_thread::sync_wait(add_42).value();                            // 5
+
+

This example demonstrates the basics of schedulers, senders, and receivers:

+
    +
  1. +

    First we need to get a scheduler from somewhere, such as a thread pool. A scheduler is a lightweight handle to an execution resource.

    +
  2. +

    To start a chain of work on a scheduler, we call § 4.19.1 execution::schedule, which returns a sender that completes on the scheduler. A sender describes asynchronous work and sends a signal (value, error, or stopped) to some recipient(s) when that work completes.

    +
  3. +

    We use sender algorithms to produce senders and compose asynchronous work. § 4.20.2 execution::then is a sender adaptor that takes an input sender and a std::invocable, and calls the std::invocable on the signal sent by the input sender. The sender returned by then sends the result of that invocation. In this case, the input sender came from schedule, so its void, meaning it won’t send us a value, so our std::invocable takes no parameters. But we return an int, which will be sent to the next recipient.

    +
  4. +

    Now, we add another operation to the chain, again using § 4.20.2 execution::then. This time, we get sent a value - the int from the previous step. We add 42 to it, and then return the result.

    +
  5. +

    Finally, we’re ready to submit the entire asynchronous pipeline and wait for its completion. Everything up until this point has been completely asynchronous; the work may not have even started yet. To ensure the work has started and then block pending its completion, we use § 4.21.2 this_thread::sync_wait, which will either return a std::optional<std::tuple<...>> with the value sent by the last sender, or an empty std::optional if the last sender sent a stopped signal, or it throws an exception if the last sender sent an error.

    +
+

1.3.2. Asynchronous inclusive scan

+
using namespace std::execution;
+
+sender auto async_inclusive_scan(scheduler auto sch,                          // 2
+                                 std::span<const double> input,               // 1
+                                 std::span<double> output,                    // 1
+                                 double init,                                 // 1
+                                 std::size_t tile_count)                      // 3
+{
+  std::size_t const tile_size = (input.size() + tile_count - 1) / tile_count;
+
+  std::vector<double> partials(tile_count + 1);                               // 4
+  partials[0] = init;                                                         // 4
+
+  return just(std::move(partials))                                            // 5
+       | transfer(sch)
+       | bulk(tile_count,                                                     // 6
+           [ = ](std::size_t i, std::vector<double>& partials) {              // 7
+             auto start = i * tile_size;                                      // 8
+             auto end   = std::min(input.size(), (i + 1) * tile_size);        // 8
+             partials[i + 1] = *--std::inclusive_scan(begin(input) + start,   // 9
+                                                      begin(input) + end,     // 9
+                                                      begin(output) + start); // 9
+           })                                                                 // 10
+       | then(                                                                // 11
+           [](std::vector<double>&& partials) {
+             std::inclusive_scan(begin(partials), end(partials),              // 12
+                                 begin(partials));                            // 12
+             return std::move(partials);                                      // 13
+           })
+       | bulk(tile_count,                                                     // 14
+           [ = ](std::size_t i, std::vector<double>& partials) {              // 14
+             auto start = i * tile_size;                                      // 14
+             auto end   = std::min(input.size(), (i + 1) * tile_size);        // 14
+             std::for_each(begin(output) + start, begin(output) + end,        // 14
+               [&] (double& e) { e = partials[i] + e; }                       // 14
+             );
+           })
+       | then(                                                                // 15
+           [ = ](std::vector<double>&& partials) {                            // 15
+             return output;                                                   // 15
+           });                                                                // 15
+}
+
+

This example builds an asynchronous computation of an inclusive scan:

+
    +
  1. +

    It scans a sequence of doubles (represented as the std::span<const double> input) and stores the result in another sequence of doubles (represented as std::span<double> output).

    +
  2. +

    It takes a scheduler, which specifies what execution resource the scan should be launched on.

    +
  3. +

    It also takes a tile_count parameter that controls the number of execution agents that will be spawned.

    +
  4. +

    First we need to allocate temporary storage needed for the algorithm, which we’ll do with a std::vector, partials. We need one double of temporary storage for each execution agent we create.

    +
  5. +

    Next we’ll create our initial sender with § 4.19.2 execution::just and § 4.20.1 execution::transfer. These senders will send the temporary storage, which we’ve moved into the sender. The sender has a completion scheduler of sch, which means the next item in the chain will use sch.

    +
  6. +

    Senders and sender adaptors support composition via operator|, similar to C++ ranges. We’ll use operator| to attach the next piece of work, which will spawn tile_count execution agents using § 4.20.9 execution::bulk (see § 4.12 Most sender adaptors are pipeable for details).

    +
  7. +

    Each agent will call a std::invocable, passing it two arguments. The first is the agent’s index (i) in the § 4.20.9 execution::bulk operation, in this case a unique integer in [0, tile_count). The second argument is what the input sender sent - the temporary storage.

    +
  8. +

    We start by computing the start and end of the range of input and output elements that this agent is responsible for, based on our agent index.

    +
  9. +

    Then we do a sequential std::inclusive_scan over our elements. We store the scan result for our last element, which is the sum of all of our elements, in our temporary storage partials.

    +
  10. +

    After all computation in that initial § 4.20.9 execution::bulk pass has completed, every one of the spawned execution agents will have written the sum of its elements into its slot in partials.

    +
  11. +

    Now we need to scan all of the values in partials. We’ll do that with a single execution agent which will execute after the § 4.20.9 execution::bulk completes. We create that execution agent with § 4.20.2 execution::then.

    +
  12. +

    § 4.20.2 execution::then takes an input sender and an std::invocable and calls the std::invocable with the value sent by the input sender. Inside our std::invocable, we call std::inclusive_scan on partials, which the input senders will send to us.

    +
  13. +

    Then we return partials, which the next phase will need.

    +
  14. +

    Finally we do another § 4.20.9 execution::bulk of the same shape as before. In this § 4.20.9 execution::bulk, we will use the scanned values in partials to integrate the sums from other tiles into our elements, completing the inclusive scan.

    +
  15. +

    async_inclusive_scan returns a sender that sends the output std::span<double>. A consumer of the algorithm can chain additional work that uses the scan result. At the point at which async_inclusive_scan returns, the computation may not have completed. In fact, it may not have even started.

    +
+

1.3.3. Asynchronous dynamically-sized read

+
using namespace std::execution;
+
+sender_of<std::size_t> auto async_read(                                       // 1
+    sender_of<std::span<std::byte>> auto buffer,                              // 1
+    auto handle);                                                             // 1
+
+struct dynamic_buffer {                                                       // 3
+  std::unique_ptr<std::byte[]> data;                                          // 3
+  std::size_t size;                                                           // 3
+};                                                                            // 3
+
+sender_of<dynamic_buffer> auto async_read_array(auto handle) {                // 2
+  return just(dynamic_buffer{})                                               // 4
+       | let_value([handle] (dynamic_buffer& buf) {                           // 5
+           return just(std::as_writeable_bytes(std::span(&buf.size, 1))       // 6
+                | async_read(handle)                                          // 7
+                | then(                                                       // 8
+                    [&buf] (std::size_t bytes_read) {                         // 9
+                      assert(bytes_read == sizeof(buf.size));                 // 10
+                      buf.data = std::make_unique<std::byte[]>(buf.size);     // 11
+                      return std::span(buf.data.get(), buf.size);             // 12
+                    })
+                | async_read(handle)                                          // 13
+                | then(
+                    [&buf] (std::size_t bytes_read) {
+                      assert(bytes_read == buf.size);                         // 14
+                      return std::move(buf);                                  // 15
+                    });
+       });
+}
+
+

This example demonstrates a common asynchronous I/O pattern - reading a payload of a dynamic size by first reading the size, then reading the number of bytes specified by the size:

+
    +
  1. +

    async_read is a pipeable sender adaptor. It’s a customization point object, but this is what it’s call signature looks like. It takes a sender parameter which must send an input buffer in the form of a std::span<std::byte>, and a handle to an I/O context. It will asynchronously read into the input buffer, up to the size of the std::span. It returns a sender which will send the number of bytes read once the read completes.

    +
  2. +

    async_read_array takes an I/O handle and reads a size from it, and then a buffer of that many bytes. It returns a sender that sends a dynamic_buffer object that owns the data that was sent.

    +
  3. +

    dynamic_buffer is an aggregate struct that contains a std::unique_ptr<std::byte[]> and a size.

    +
  4. +

    The first thing we do inside of async_read_array is create a sender that will send a new, empty dynamic_array object using § 4.19.2 execution::just. We can attach more work to the pipeline using operator| composition (see § 4.12 Most sender adaptors are pipeable for details).

    +
  5. +

    We need the lifetime of this dynamic_array object to last for the entire pipeline. So, we use let_value, which takes an input sender and a std::invocable that must return a sender itself (see § 4.20.4 execution::let_* for details). let_value sends the value from the input sender to the std::invocable. Critically, the lifetime of the sent object will last until the sender returned by the std::invocable completes.

    +
  6. +

    Inside of the let_value std::invocable, we have the rest of our logic. First, we want to initiate an async_read of the buffer size. To do that, we need to send a std::span pointing to buf.size. We can do that with § 4.19.2 execution::just.

    +
  7. +

    We chain the async_read onto the § 4.19.2 execution::just sender with operator|.

    +
  8. +

    Next, we pipe a std::invocable that will be invoked after the async_read completes using § 4.20.2 execution::then.

    +
  9. +

    That std::invocable gets sent the number of bytes read.

    +
  10. +

    We need to check that the number of bytes read is what we expected.

    +
  11. +

    Now that we have read the size of the data, we can allocate storage for it.

    +
  12. +

    We return a std::span<std::byte> to the storage for the data from the std::invocable. This will be sent to the next recipient in the pipeline.

    +
  13. +

    And that recipient will be another async_read, which will read the data.

    +
  14. +

    Once the data has been read, in another § 4.20.2 execution::then, we confirm that we read the right number of bytes.

    +
  15. +

    Finally, we move out of and return our dynamic_buffer object. It will get sent by the sender returned by async_read_array. We can attach more things to that sender to use the data in the buffer.

    +
+

1.4. Asynchronous Windows socket recv

+

To get a better feel for how this interface might be used by low-level operations see this example implementation +of a cancellable async_recv() operation for a Windows Socket.

+
struct operation_base : WSAOVERALAPPED {
+    using completion_fn = void(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept;
+
+    // Assume IOCP event loop will call this when this OVERLAPPED structure is dequeued.
+    completion_fn* completed;
+};
+
+template<typename Receiver>
+struct recv_op : operation_base {
+    recv_op(SOCKET s, void* data, size_t len, Receiver r)
+    : receiver(std::move(r))
+    , sock(s) {
+        this->Internal = 0;
+        this->InternalHigh = 0;
+        this->Offset = 0;
+        this->OffsetHigh = 0;
+        this->hEvent = NULL;
+        this->completed = &recv_op::on_complete;
+        buffer.len = len;
+        buffer.buf = static_cast<CHAR*>(data);
+    }
+
+    friend void tag_invoke(std::execution::start_t, recv_op& self) noexcept {
+        // Avoid even calling WSARecv() if operation already cancelled
+        auto st = std::execution::get_stop_token(
+          std::execution::get_env(self.receiver));
+        if (st.stop_requested()) {
+            std::execution::set_stopped(std::move(self.receiver));
+            return;
+        }
+
+        // Store and cache result here in case it changes during execution
+        const bool stopPossible = st.stop_possible();
+        if (!stopPossible) {
+            self.ready.store(true, std::memory_order_relaxed);
+        }
+
+        // Launch the operation
+        DWORD bytesTransferred = 0;
+        DWORD flags = 0;
+        int result = WSARecv(self.sock, &self.buffer, 1, &bytesTransferred, &flags,
+                             static_cast<WSAOVERLAPPED*>(&self), NULL);
+        if (result == SOCKET_ERROR) {
+            int errorCode = WSAGetLastError();
+            if (errorCode != WSA_IO_PENDING) {
+                if (errorCode == WSA_OPERATION_ABORTED) {
+                    std::execution::set_stopped(std::move(self.receiver));
+                } else {
+                    std::execution::set_error(std::move(self.receiver),
+                                              std::error_code(errorCode, std::system_category()));
+                }
+                return;
+            }
+        } else {
+            // Completed synchronously (assuming FILE_SKIP_COMPLETION_PORT_ON_SUCCESS has been set)
+            execution::set_value(std::move(self.receiver), bytesTransferred);
+            return;
+        }
+
+        // If we get here then operation has launched successfully and will complete asynchronously.
+        // May be completing concurrently on another thread already.
+        if (stopPossible) {
+            // Register the stop callback
+            self.stopCallback.emplace(std::move(st), cancel_cb{self});
+
+            // Mark as 'completed'
+            if (self.ready.load(std::memory_order_acquire) ||
+                self.ready.exchange(true, std::memory_order_acq_rel)) {
+                // Already completed on another thread
+                self.stopCallback.reset();
+
+                BOOL ok = WSAGetOverlappedResult(self.sock, (WSAOVERLAPPED*)&self, &bytesTransferred, FALSE, &flags);
+                if (ok) {
+                    std::execution::set_value(std::move(self.receiver), bytesTransferred);
+                } else {
+                    int errorCode = WSAGetLastError();
+                    std::execution::set_error(std::move(self.receiver),
+                                              std::error_code(errorCode, std::system_category()));
+                }
+            }
+        }
+    }
+
+    struct cancel_cb {
+        recv_op& op;
+
+        void operator()() noexcept {
+            CancelIoEx((HANDLE)op.sock, (OVERLAPPED*)(WSAOVERLAPPED*)&op);
+        }
+    };
+
+    static void on_complete(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept {
+        recv_op& self = *static_cast<recv_op*>(op);
+
+        if (ready.load(std::memory_order_acquire) ||
+            ready.exchange(true, std::memory_order_acq_rel)) {
+            // Unsubscribe any stop-callback so we know that CancelIoEx() is not accessing 'op'
+            // any more
+            stopCallback.reset();
+
+            if (errorCode == 0) {
+                std::execution::set_value(std::move(receiver), bytesTransferred);
+            } else {
+                std::execution::set_error(std::move(receiver),
+                                          std::error_code(errorCode, std::system_category()));
+            }
+        }
+    }
+
+    Receiver receiver;
+    SOCKET sock;
+    WSABUF buffer;
+    std::optional<typename stop_callback_type_t<Receiver>
+        ::template callback_type<cancel_cb>> stopCallback;
+    std::atomic<bool> ready{false};
+};
+
+struct recv_sender {
+    using sender_concept = std::execution::sender_t;
+    SOCKET sock;
+    void* data;
+    size_t len;
+
+    template<typename Receiver>
+    friend recv_op<Receiver> tag_invoke(std::execution::connect_t,
+                                        const recv_sender& s,
+                                        Receiver r) {
+        return recv_op<Receiver>{s.sock, s.data, s.len, std::move(r)};
+    }
+};
+
+recv_sender async_recv(SOCKET s, void* data, size_t len) {
+    return recv_sender{s, data, len};
+}
+
+

1.4.1. More end-user examples

+
1.4.1.1. Sudoku solver
+

This example comes from Kirk Shoop, who ported an example from TBB’s documentation to sender/receiver in his fork of the libunifex repo. It is a Sudoku solver that uses a configurable number of threads to explore the search space for solutions.

+

The sender/receiver-based Sudoku solver can be found here. Some things that are worth noting about Kirk’s solution:

+
    +
  1. +

    Although it schedules asychronous work onto a thread pool, and each unit of work will schedule more work, its use of structured concurrency patterns make reference counting unnecessary. The solution does not make use of shared_ptr.

    +
  2. +

    In addition to eliminating the need for reference counting, the use of structured concurrency makes it easy to ensure that resources are cleaned up on all code paths. In contrast, the TBB example that inspired this one leaks memory.

    +
+

For comparison, the TBB-based Sudoku solver can be found here.

+
1.4.1.2. File copy
+

This example also comes from Kirk Shoop which uses sender/receiver to recursively copy the files a directory tree. It demonstrates how sender/receiver can be used to do IO, using a scheduler that schedules work on Linux’s io_uring.

+

As with the Sudoku example, this example obviates the need for reference counting by employing structured concurrency. It uses iteration with an upper limit to avoid having too many open file handles.

+

You can find the example here.

+
1.4.1.3. Echo server
+

Dietmar Kuehl has a hobby project that implements networking APIs on top of sender/receiver. He recently implemented an echo server as a demo. His echo server code can be found here.

+

Below, I show the part of the echo server code. This code is executed for each client that connects to the echo server. In a loop, it reads input from a socket and echos the input back to the same socket. All of this, including the loop, is implemented with generic async algorithms.

+
outstanding.start(
+    EX::repeat_effect_until(
+          EX::let_value(
+              NN::async_read_some(ptr->d_socket,
+                                  context.scheduler(),
+                                  NN::buffer(ptr->d_buffer))
+        | EX::then([ptr](::std::size_t n){
+            ::std::cout << "read='" << ::std::string_view(ptr->d_buffer, n) << "'\n";
+            ptr->d_done = n == 0;
+            return n;
+        }),
+          [&context, ptr](::std::size_t n){
+            return NN::async_write_some(ptr->d_socket,
+                                        context.scheduler(),
+                                        NN::buffer(ptr->d_buffer, n));
+          })
+        | EX::then([](auto&&...){})
+        , [owner = ::std::move(owner)]{ return owner->d_done; }
+    )
+);
+
+

In this code, NN::async_read_some and NN::async_write_some are asynchronous socket-based networking APIs that return senders. EX::repeat_effect_until, EX::let_value, and EX::then are fully generic sender adaptor algorithms that accept and return senders.

+

This is a good example of seamless composition of async IO functions with non-IO operations. And by composing the senders in this structured way, all the state for the composite operation -- the repeat_effect_until expression and all its child operations -- is stored altogether in a single object.

+

1.5. Examples: Algorithms

+

In this section we show a few simple sender/receiver-based algorithm implementations.

+

1.5.1. then

+
namespace exec = std::execution;
+
+template<class R, class F>
+class _then_receiver
+    : exec::receiver_adaptor<_then_receiver<R, F>, R> {
+  friend exec::receiver_adaptor<_then_receiver, R>;
+  F f_;
+
+  // Customize set_value by invoking the callable and passing the result to the inner receiver
+  template<class... As>
+  void set_value(As&&... as) && noexcept try {
+    exec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...));
+  } catch(...) {
+    exec::set_error(std::move(*this).base(), std::current_exception());
+  }
+
+ public:
+  _then_receiver(R r, F f)
+   : exec::receiver_adaptor<_then_receiver, R>{std::move(r)}
+   , f_(std::move(f)) {}
+};
+
+template<exec::sender S, class F>
+struct _then_sender {
+  using sender_concept = exec::sender_t;
+  S s_;
+  F f_;
+
+  template <class... Args>
+    using _set_value_t = exec::completion_signatures<
+      exec::set_value_t(std::invoke_result_t<F, Args...>)>;
+
+  // Compute the completion signatures
+  template<class Env>
+  friend auto tag_invoke(exec::get_completion_signatures_t, _then_sender&&, Env)
+    -> exec::transform_completion_signatures_of<S, Env,
+        exec::completion_signatures<exec::set_error_t(std::exception_ptr)>,
+        _set_value_t>;
+
+  // Connect:
+  template<exec::receiver R>
+  friend auto tag_invoke(exec::connect_t, _then_sender&& self, R r)
+    -> exec::connect_result_t<S, _then_receiver<R, F>> {
+      return exec::connect(
+        (S&&) self.s_, _then_receiver<R, F>{(R&&) r, (F&&) self.f_});
+  }
+
+  friend decltype(auto) tag_invoke(get_env_t, const _then_sender& self) noexcept {
+    return get_env(self.s_);
+  }
+};
+
+template<exec::sender S, class F>
+exec::sender auto then(S s, F f) {
+  return _then_sender<S, F>{(S&&) s, (F&&) f};
+}
+
+

This code builds a then algorithm that transforms the value(s) from the input sender +with a transformation function. The result of the transformation becomes the new value. +The other receiver functions (set_error and set_stopped), as well as all receiver queries, +are passed through unchanged.

+

In detail, it does the following:

+
    +
  1. +

    Defines a receiver in terms of execution::receiver_adaptor that aggregates +another receiver and an invocable that:

    +
      +
    • +

      Defines a constrained tag_invoke overload for transforming the value +channel.

      +
    • +

      Defines another constrained overload of tag_invoke that passes all other +customizations through unchanged.

      +
    +

    The tag_invoke overloads are actually implemented by execution::receiver_adaptor; they dispatch either to named members, as +shown above with _then_receiver::set_value, or to the adapted receiver.

    +
  2. +

    Defines a sender that aggregates another sender and the invocable, which defines a tag_invoke customization for std::execution::connect that wraps the incoming receiver in the receiver from (1) and passes it and the incoming sender to std::execution::connect, returning the result. It also defines a tag_invoke customization of get_completion_signatures that declares the sender’s completion signatures when executed within a particular environment.

    +
+

1.5.2. retry

+
using namespace std;
+namespace exec = execution;
+
+template <class From, class To>
+concept _decays_to = same_as<decay_t<From>, To>;
+
+// _conv needed so we can emplace construct non-movable types into
+// a std::optional.
+template<invocable F>
+  requires is_nothrow_move_constructible_v<F>
+struct _conv {
+  F f_;
+  explicit _conv(F f) noexcept : f_((F&&) f) {}
+  operator invoke_result_t<F>() && {
+    return ((F&&) f_)();
+  }
+};
+
+template<class S, class R>
+struct _op;
+
+// pass through all customizations except set_error, which retries the operation.
+template<class S, class R>
+struct _retry_receiver
+  : exec::receiver_adaptor<_retry_receiver<S, R>> {
+  _op<S, R>* o_;
+
+  R&& base() && noexcept { return (R&&) o_->r_; }
+  const R& base() const & noexcept { return o_->r_; }
+
+  explicit _retry_receiver(_op<S, R>* o) : o_(o) {}
+
+  void set_error(auto&&) && noexcept {
+    o_->_retry(); // This causes the op to be retried
+  }
+};
+
+// Hold the nested operation state in an optional so we can
+// re-construct and re-start it if the operation fails.
+template<class S, class R>
+struct _op {
+  S s_;
+  R r_;
+  optional<
+      exec::connect_result_t<S&, _retry_receiver<S, R>>> o_;
+
+  _op(S s, R r): s_((S&&)s), r_((R&&)r), o_{_connect()} {}
+  _op(_op&&) = delete;
+
+  auto _connect() noexcept {
+    return _conv{[this] {
+      return exec::connect(s_, _retry_receiver<S, R>{this});
+    }};
+  }
+  void _retry() noexcept try {
+    o_.emplace(_connect()); // potentially-throwing
+    exec::start(*o_);
+  } catch(...) {
+    exec::set_error((R&&) r_, std::current_exception());
+  }
+  friend void tag_invoke(exec::start_t, _op& o) noexcept {
+    exec::start(*o.o_);
+  }
+};
+
+template<class S>
+struct _retry_sender {
+  using sender_concept = exec::sender_t;
+  S s_;
+  explicit _retry_sender(S s) : s_((S&&) s) {}
+
+  template <class... Ts>
+    using _value_t =
+      exec::completion_signatures<exec::set_value_t(Ts...)>;
+  template <class>
+    using _error_t = exec::completion_signatures<>;
+
+  // Declare the signatures with which this sender can complete
+  template <class Env>
+  friend auto tag_invoke(exec::get_completion_signatures_t, const _retry_sender&, Env)
+    -> exec::transform_completion_signatures_of<S&, Env,
+        exec::completion_signatures<exec::set_error_t(std::exception_ptr)>,
+        _value_t, _error_t>;
+
+  template<exec::receiver R>
+  friend _op<S, R> tag_invoke(exec::connect_t, _retry_sender&& self, R r) {
+    return {(S&&) self.s_, (R&&) r};
+  }
+
+  friend decltype(auto) tag_invoke(exec::get_env_t, const _retry_sender& self) noexcept {
+    return get_env(self.s_);
+  }
+};
+
+template<exec::sender S>
+exec::sender auto retry(S s) {
+  return _retry_sender{(S&&) s};
+}
+
+

The retry algorithm takes a multi-shot sender and causes it to repeat on error, passing +through values and stopped signals. Each time the input sender is restarted, a new receiver +is connected and the resulting operation state is stored in an optional, which allows us +to reinitialize it multiple times.

+

This example does the following:

+
    +
  1. +

    Defines a _conv utility that takes advantage of C++17’s guaranteed copy elision to +emplace a non-movable type in a std::optional.

    +
  2. +

    Defines a _retry_receiver that holds a pointer back to the operation state. It passes +all customizations through unmodified to the inner receiver owned by the operation state +except for set_error, which causes a _retry() function to be called instead.

    +
  3. +

    Defines an operation state that aggregates the input sender and receiver, and declares +storage for the nested operation state in an optional. Constructing the operation +state constructs a _retry_receiver with a pointer to the (under construction) operation +state and uses it to connect to the aggregated sender.

    +
  4. +

    Starting the operation state dispatches to start on the inner operation state.

    +
  5. +

    The _retry() function reinitializes the inner operation state by connecting the sender +to a new receiver, holding a pointer back to the outer operation state as before.

    +
  6. +

    After reinitializing the inner operation state, _retry() calls start on it, causing +the failed operation to be rescheduled.

    +
  7. +

    Defines a _retry_sender that implements the connect customization point to return +an operation state constructed from the passed-in sender and receiver.

    +
  8. +

    _retry_sender also implements the get_completion_signatures customization point to describe the ways this sender may complete when executed in a particular execution resource.

    +
+

1.6. Examples: Schedulers

+

In this section we look at some schedulers of varying complexity.

+

1.6.1. Inline scheduler

+
class inline_scheduler {
+  template <class R>
+    struct _op {
+      [[no_unique_address]] R rec_;
+      friend void tag_invoke(std::execution::start_t, _op& op) noexcept {
+        std::execution::set_value((R&&) op.rec_);
+      }
+    };
+
+  struct _env {
+    template <class Tag>
+      friend inline_scheduler tag_invoke(
+          std::execution::get_completion_scheduler_t<Tag>, _env) noexcept {
+        return {};
+      }
+  };
+
+  struct _sender {
+    using sender_concept = std::execution::sender_t;
+    using completion_signatures =
+      std::execution::completion_signatures<std::execution::set_value_t()>;
+
+    template <class R>
+      friend auto tag_invoke(std::execution::connect_t, _sender, R&& rec)
+        noexcept(std::is_nothrow_constructible_v<std::remove_cvref_t<R>, R>)
+        -> _op<std::remove_cvref_t<R>> {
+        return {(R&&) rec};
+      }
+
+    friend _env tag_invoke(exec::get_env_t, _sender) noexcept {
+      return {};
+    }
+  };
+
+  friend _sender tag_invoke(std::execution::schedule_t, const inline_scheduler&) noexcept {
+    return {};
+  }
+
+ public:
+  inline_scheduler() = default;
+  bool operator==(const inline_scheduler&) const noexcept = default;
+};
+
+

The inline scheduler is a trivial scheduler that completes immediately and synchronously on +the thread that calls std::execution::start on the operation state produced by its sender. +In other words, start(connect(schedule(inline-scheduler), receiver)) is +just a fancy way of saying set_value(receiver), with the exception of the fact that start wants to be passed an lvalue.

+

Although not a particularly useful scheduler, it serves to illustrate the basics of +implementing one. The inline_scheduler:

+
    +
  1. +

    Customizes execution::schedule to return an instance of the sender type _sender.

    +
  2. +

    The _sender type models the sender concept and provides the metadata +needed to describe it as a sender of no values +and that never calls set_error or set_stopped. This +metadata is provided with the help of the execution::completion_signatures utility.

    +
  3. +

    The _sender type customizes execution::connect to accept a receiver of no +values. It returns an instance of type _op that holds the receiver by +value.

    +
  4. +

    The operation state customizes std::execution::start to call std::execution::set_value on the receiver.

    +
+

1.6.2. Single thread scheduler

+

This example shows how to create a scheduler for an execution resource that consists of a single +thread. It is implemented in terms of a lower-level execution resource called std::execution::run_loop.

+
class single_thread_context {
+  std::execution::run_loop loop_;
+  std::thread thread_;
+
+public:
+  single_thread_context()
+    : loop_()
+    , thread_([this] { loop_.run(); })
+  {}
+
+  ~single_thread_context() {
+    loop_.finish();
+    thread_.join();
+  }
+
+  auto get_scheduler() noexcept {
+    return loop_.get_scheduler();
+  }
+
+  std::thread::id get_thread_id() const noexcept {
+    return thread_.get_id();
+  }
+};
+
+

The single_thread_context owns an event loop and a thread to drive it. In the destructor, it tells the event +loop to finish up what it’s doing and then joins the thread, blocking for the event loop to drain.

+

The interesting bits are in the execution::run_loop context implementation. It +is slightly too long to include here, so we only provide a reference to +it, +but there is one noteworthy detail about its implementation: It uses space in +its operation states to build an intrusive linked list of work items. In +structured concurrency patterns, the operation states of nested operations +compose statically, and in an algorithm like this_thread::sync_wait, the +composite operation state lives on the stack for the duration of the operation. +The end result is that work can be scheduled onto this thread with zero +allocations.

+

1.7. Examples: Server theme

+

In this section we look at some examples of how one would use senders to implement an HTTP server. The examples ignore the low-level details of the HTTP server and looks at how senders can be combined to achieve the goals of the project.

+

General application context:

+
    +
  • +

    server application that processes images

    +
  • +

    execution resources:

    +
      +
    • +

      1 dedicated thread for network I/O

      +
    • +

      N worker threads used for CPU-intensive work

      +
    • +

      M threads for auxiliary I/O

      +
    • +

      optional GPU context that may be used on some types of servers

      +
    +
  • +

    all parts of the applications can be asynchronous

    +
  • +

    no locks shall be used in user code

    +
+

1.7.1. Composability with execution::let_*

+

Example context:

+
    +
  • +

    we are looking at the flow of processing an HTTP request and sending back the response

    +
  • +

    show how one can break the (slightly complex) flow into steps with execution::let_* functions

    +
  • +

    different phases of processing HTTP requests are broken down into separate concerns

    +
  • +

    each part of the processing might use different execution resources (details not shown in this example)

    +
  • +

    error handling is generic, regardless which component fails; we always send the right response to the clients

    +
+

Goals:

+
    +
  • +

    show how one can break more complex flows into steps with let_* functions

    +
  • +

    exemplify the use of let_value, let_error, let_stopped, and just algorithms

    +
+
namespace ex = std::execution;
+
+// Returns a sender that yields an http_request object for an incoming request
+ex::sender auto schedule_request_start(read_requests_ctx ctx) {...}
+// Sends a response back to the client; yields a void signal on success
+ex::sender auto send_response(const http_response& resp) {...}
+// Validate that the HTTP request is well-formed; forwards the request on success
+ex::sender auto validate_request(const http_request& req) {...}
+
+// Handle the request; main application logic
+ex::sender auto handle_request(const http_request& req) {
+  //...
+  return ex::just(http_response{200, result_body});
+}
+
+// Transforms server errors into responses to be sent to the client
+ex::sender auto error_to_response(std::exception_ptr err) {
+  try {
+    std::rethrow_exception(err);
+  } catch (const std::invalid_argument& e) {
+    return ex::just(http_response{404, e.what()});
+  } catch (const std::exception& e) {
+    return ex::just(http_response{500, e.what()});
+  } catch (...) {
+    return ex::just(http_response{500, "Unknown server error"});
+  }
+}
+// Transforms cancellation of the server into responses to be sent to the client
+ex::sender auto stopped_to_response() {
+  return ex::just(http_response{503, "Service temporarily unavailable"});
+}
+//...
+// The whole flow for transforming incoming requests into responses
+ex::sender auto snd =
+    // get a sender when a new request comes
+    schedule_request_start(the_read_requests_ctx)
+    // make sure the request is valid; throw if not
+    | ex::let_value(validate_request)
+    // process the request in a function that may be using a different execution resource
+    | ex::let_value(handle_request)
+    // If there are errors transform them into proper responses
+    | ex::let_error(error_to_response)
+    // If the flow is cancelled, send back a proper response
+    | ex::let_stopped(stopped_to_response)
+    // write the result back to the client
+    | ex::let_value(send_response)
+    // done
+    ;
+// execute the whole flow asynchronously
+ex::start_detached(std::move(snd));
+
+

The example shows how one can separate out the concerns for interpreting requests, validating requests, running the main logic for handling the request, generating error responses, handling cancellation and sending the response back to the client. +They are all different phases in the application, and can be joined together with the let_* functions.

+

All our functions return execution::sender objects, so that they can all generate success, failure and cancellation paths. +For example, regardless where an error is generated (reading request, validating request or handling the response), we would have one common block to handle the error, and following error flows is easy.

+

Also, because of using execution::sender objects at any step, we might expect any of these steps to be completely asynchronous; the overall flow doesn’t care. +Regardless of the execution resource in which the steps, or part of the steps are executed in, the flow is still the same.

+

1.7.2. Moving between execution resources with execution::on and execution::transfer

+

Example context:

+
    +
  • +

    reading data from the socket before processing the request

    +
  • +

    reading of the data is done on the I/O context

    +
  • +

    no processing of the data needs to be done on the I/O context

    +
+

Goals:

+
    +
  • +

    show how one can change the execution resource

    +
  • +

    exemplify the use of on and transfer algorithms

    +
+
namespace ex = std::execution;
+
+size_t legacy_read_from_socket(int sock, char* buffer, size_t buffer_len) {}
+void process_read_data(const char* read_data, size_t read_len) {}
+//...
+
+// A sender that just calls the legacy read function
+auto snd_read = ex::just(sock, buf, buf_len) | ex::then(legacy_read_from_socket);
+// The entire flow
+auto snd =
+    // start by reading data on the I/O thread
+    ex::on(io_sched, std::move(snd_read))
+    // do the processing on the worker threads pool
+    | ex::transfer(work_sched)
+    // process the incoming data (on worker threads)
+    | ex::then([buf](int read_len) { process_read_data(buf, read_len); })
+    // done
+    ;
+// execute the whole flow asynchronously
+ex::start_detached(std::move(snd));
+
+

The example assume that we need to wrap some legacy code of reading sockets, and handle execution resource switching. +(This style of reading from socket may not be the most efficient one, but it’s working for our purposes.) +For performance reasons, the reading from the socket needs to be done on the I/O thread, and all the processing needs to happen on a work-specific execution resource (i.e., thread pool).

+

Calling execution::on will ensure that the given sender will be started on the given scheduler. +In our example, snd_read is going to be started on the I/O scheduler. +This sender will just call the legacy code.

+

The completion-signal will be issued in the I/O execution resource, so we have to move it to the work thread pool. +This is achieved with the help of the execution::transfer algorithm. +The rest of the processing (in our case, the last call to then) will happen in the work thread pool.

+

The reader should notice the difference between execution::on and execution::transfer. +The execution::on algorithm will ensure that the given sender will start in the specified context, and doesn’t care where the completion-signal for that sender is sent. +The execution::transfer algorithm will not care where the given sender is going to be started, but will ensure that the completion-signal of will be transferred to the given context.

+

1.8. What this proposal is not

+

This paper is not a patch on top of A Unified Executors Proposal for C++; we are not asking to update the existing paper, we are asking to retire it in favor of this paper, which is already self-contained; any example code within this paper can be written in Standard C++, without the need +to standardize any further facilities.

+

This paper is not an alternative design to A Unified Executors Proposal for C++; rather, we have taken the design in the current executors paper, and applied targeted fixes to allow it to fulfill the promises of the sender/receiver model, as well as provide all the facilities we consider +essential when writing user code using standard execution concepts; we have also applied the guidance of removing one-way executors from the paper entirely, and instead provided an algorithm based around senders that serves the same purpose.

+

1.9. Design changes from P0443

+
    +
  1. +

    The executor concept has been removed and all of its proposed functionality +is now based on schedulers and senders, as per SG1 direction.

    +
  2. +

    Properties are not included in this paper. We see them as a possible future +extension, if the committee gets more comfortable with them.

    +
  3. +

    Senders now advertise what scheduler, if any, their evaluation will complete +on.

    +
  4. +

    The places of execution of user code in P0443 weren’t precisely defined, +whereas they are in this paper. See § 4.5 Senders can propagate completion schedulers.

    +
  5. +

    P0443 did not propose a suite of sender algorithms necessary for writing +sender code; this paper does. See § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers.

    +
  6. +

    P0443 did not specify the semantics of variously qualified connect overloads; this paper does. See § 4.7 Senders can be either multi-shot or single-shot.

    +
  7. +

    This paper extends the sender traits/typed sender design to support typed +senders whose value/error types depend on type information provided late via +the receiver.

    +
  8. +

    Support for untyped senders is dropped; the typed_sender concept is renamed sender; sender_traits is replaced with completion_signatures_of_t.

    +
  9. +

    Specific type erasure facilities are omitted, as per LEWG direction. Type +erasure facilities can be built on top of this proposal, as discussed in § 5.9 Ranges-style CPOs vs tag_invoke.

    +
  10. +

    A specific thread pool implementation is omitted, as per LEWG direction.

    +
  11. +

    Some additional utilities are added:

    +
      +
    • +

      run_loop: An execution resource that provides a multi-producer, +single-consumer, first-in-first-out work queue.

      +
    • +

      receiver_adaptor: A utility for algorithm authors for defining one +receiver type in terms of another.

      +
    • +

      completion_signatures and transform_completion_signatures: +Utilities for describing the ways in which a sender can complete in a +declarative syntax.

      +
    +
+

1.10. Prior art

+

This proposal builds upon and learns from years of prior art with asynchronous and parallel programming frameworks in C++. In this section, we discuss async abstractions that have previously been suggested as a possible basis for asynchronous algorithms and why they fall short.

+

1.10.1. Futures

+

A future is a handle to work that has already been scheduled for execution. It is one end of a communication channel; the other end is a promise, used to receive the result from the concurrent operation and to communicate it to the future.

+

Futures, as traditionally realized, require the dynamic allocation and management of a shared state, synchronization, and typically type-erasure of work and continuation. Many of these costs are inherent in the nature of "future" as a handle to work that is already scheduled for execution. These expenses rule out the future abstraction for many uses and makes it a poor choice for a basis of a generic mechanism.

+

1.10.2. Coroutines

+

C++20 coroutines are frequently suggested as a basis for asynchronous algorithms. It’s fair to ask why, if we added coroutines to C++, are we suggesting the addition of a library-based abstraction for asynchrony. Certainly, coroutines come with huge syntactic and semantic advantages over the alternatives.

+

Although coroutines are lighter weight than futures, coroutines suffer many of the same problems. Since they typically start suspended, they can avoid synchronizing the chaining of dependent work. However in many cases, coroutine frames require an unavoidable dynamic allocation and indirect function calls. This is done to hide the layout of the coroutine frame from the C++ type system, which in turn makes possible the separate compilation of coroutines and certain compiler optimizations, such as optimization of the coroutine frame size.

+

Those advantages come at a cost, though. Because of the dynamic allocation of coroutine frames, coroutines in embedded or heterogeneous environments, which often lack support for dynamic allocation, require great attention to detail. And the allocations and indirections tend to complicate the job of the inliner, often resulting in sub-optimal codegen.

+

The coroutine language feature mitigates these shortcomings somewhat with the HALO optimization Halo: coroutine Heap Allocation eLision Optimization: the joint response, which leverages existing compiler optimizations such as allocation elision and devirtualization to inline the coroutine, completely eliminating the runtime overhead. However, HALO requires a sophisiticated compiler, and a fair number of stars need to align for the optimization to kick in. In our experience, more often than not in real-world code today’s compilers are not able to inline the coroutine, resulting in allocations and indirections in the generated code.

+

In a suite of generic async algorithms that are expected to be callable from hot code paths, the extra allocations and indirections are a deal-breaker. It is for these reasons that we consider coroutines a poor choise for a basis of all standard async.

+

1.10.3. Callbacks

+

Callbacks are the oldest, simplest, most powerful, and most efficient mechanism for creating chains of work, but suffer problems of their own. Callbacks must propagate either errors or values. This simple requirement yields many different interface possibilities. The lack of a standard callback shape obstructs generic design.

+

Additionally, few of these possibilities accommodate cancellation signals when the user requests upstream work to stop and clean up.

+

1.11. Field experience

+

1.11.1. libunifex

+

This proposal draws heavily from our field experience with libunifex. Libunifex implements all of the concepts and customization points defined in this paper (with slight variations -- the design of P2300 has evolved due to LEWG feedback), many of this paper’s algorithms (some under different names), and much more besides.

+

Libunifex has several concrete schedulers in addition to the run_loop suggested here (where it is called manual_event_loop). It has schedulers that dispatch efficiently to epoll and io_uring on Linux and the Windows Thread Pool on Windows.

+

In addition to the proposed interfaces and the additional schedulers, it has several important extensions to the facilities described in this paper, which demonstrate directions in which these abstractions may be evolved over time, including:

+
    +
  • +

    Timed schedulers, which permit scheduling work on an execution resource at a particular time or after a particular duration has elapsed. In addition, it provides time-based algorithms.

    +
  • +

    File I/O schedulers, which permit filesystem I/O to be scheduled.

    +
  • +

    Two complementary abstractions for streams (asynchronous ranges), and a set of stream-based algorithms.

    +
+

Libunifex has seen heavy production use at Facebook. As of October 2021, it is currently used in production within the following applications and platforms:

+
    +
  • +

    Facebook Messenger on iOS, Android, Windows, and macOS

    +
  • +

    Instagram on iOS and Android

    +
  • +

    Facebook on iOS and Android

    +
  • +

    Portal

    +
  • +

    An internal Facebook product that runs on Linux

    +
+

All of these applications are making direct use of the sender/receiver abstraction as presented in this paper. One product (Instagram on iOS) is making use of the sender/coroutine integration as presented. The monthly active users of these products number in the billions.

+

1.11.2. Other implementations

+

The authors are aware of a number of other implementations of sender/receiver from this paper. These are presented here in perceived order of maturity and field experience.

+
    +
  • +

    HPX - The C++ Standard Library for Parallelism and Concurrency

    +

    HPX is a general purpose C++ runtime system for parallel and distributed applications that has been under active development since 2007. HPX exposes a uniform, standards-oriented API, and keeps abreast of the latest standards and proposals. It is used in a wide variety of high-performance applications.

    +

    The sender/receiver implementation in HPX has been under active development since May 2020. It is used to erase the overhead of futures and to make it possible to write efficient generic asynchronous algorithms that are agnostic to their execution resource. In HPX, algorithms can migrate execution between execution resources, even to GPUs and back, using a uniform standard interface with sender/receiver.

    +

    Far and away, the HPX team has the greatest usage experience outside Facebook. Mikael Simberg summarizes the experience as follows:

    +
    +

    Summarizing, for us the major benefits of sender/receiver compared to the old model are:

    +
      +
    1. +

      Proper hooks for transitioning between execution resources.

      +
    2. +

      The adaptors. Things like let_value are really nice additions.

      +
    3. +

      Separation of the error channel from the value channel (also cancellation, but we don’t have much use for it at the moment). Even from a teaching perspective having to explain that the future f2 in the continuation will always be ready here f1.then([](future<T> f2) {...}) is enough of a reason to separate the channels. All the other obvious reasons apply as well of course.

      +
    4. +

      For futures we have a thing called hpx::dataflow which is an optimized version of when_all(...).then(...) which avoids intermediate allocations. With the sender/receiver when_all(...) | then(...) we get that "for free".

      +
    +
    +
  • +

    kuhllib by Dietmar Kuehl

    +

    This is a prototype Standard Template Library with an implementation of sender/receiver that has been under development since May, 2021. It is significant mostly for its support for sender/receiver-based networking interfaces.

    +

    Here, Dietmar Kuehl speaks about the perceived complexity of sender/receiver:

    +
    +

    ... and, also similar to STL: as I had tried to do things in that space before I recognize sender/receivers as being maybe complicated in one way but a huge simplification in another one: like with STL I think those who use it will benefit - if not from the algorithm from the clarity of abstraction: the separation of concerns of STL (the algorithm being detached from the details of the sequence representation) is a major leap. Here it is rather similar: the separation of the asynchronous algorithm from the details of execution. Sure, there is some glue to tie things back together but each of them is simpler than the combined result.

    +
    +

    Elsewhere, he said:

    +
    +

    ... to me it feels like sender/receivers are like iterators when STL emerged: they are different from what everybody did in that space. However, everything people are already doing in that space isn’t right.

    +
    +

    Kuehl also has experience teaching sender/receiver at Bloomberg. About that experience he says:

    +
    +

    When I asked [my students] specifically about how complex they consider the sender/receiver stuff the feedback was quite unanimous that the sender/receiver parts aren’t trivial but not what contributes to the complexity.

    +
    +
  • +

    The reference implementation

    +

    This is a complete implementation written from the specification in this paper. Its primary purpose is to help find specification bugs and to harden the wording of the proposal. It is +fit for broad use and for contribution to libc++.

    +

    It is current with R8 of this paper.

    +
  • +

    Reference implementation for the Microsoft STL by Michael Schellenberger Costa

    +

    This is another reference implementation of this proposal, this time in a fork of the Mircosoft STL implementation. Michael Schellenberger Costa is not affiliated with Microsoft. He intends to contribute this implementation upstream when it is complete.

    +
+

1.11.3. Inspirations

+

This proposal also draws heavily from our experience with Thrust and Agency. It is also inspired by the needs of countless other C++ frameworks for asynchrony, parallelism, and concurrency, including:

+ +

2. Revision history

+

2.1. R8

+

The changes since R7 are as follows:

+

Fixes:

+
    +
  • +

    get_env(obj) is required to be nothrow.

    +
  • +

    get_env and the associated environment utilities are moved back into std::execution from std::.

    +
  • +

    make_completion_signatures is renamed transform_completion_signatures_of and is expressed in terms of the new transform_completion_signatures, +which takes an input set of completion signatures instead of a sender and an +environment.

    +
  • +

    Add a requirement on queryable objects that if tag_invoke(query, env, args...) is well-formed, then query(env, args...) is +expression-equivalent to it. This is necessary to properly specify how to +join two environments in the presence of queries that have defaults.

    +
  • +

    The sender_in<Sndr, Env> concept requires that E satisfies queryable.

    +
  • +

    Senders of more than one value are now co_await-able in coroutines, the +result of which is a std::tuple of the values (which is suitable as the +initializer of a structured binding).

    +
+

Enhancements:

+
    +
  • +

    The exposition-only class template basic-sender is greatly +enhanced, and the sender algorithms are respecified in term of it.

    +
  • +

    enable_sender and enable_receiver traits now have default +implementations that look for nested sender_concept and receiver_concept types, respectively.

    +
+

2.2. R7

+

The changes since R6 are as follows:

+

Fixes:

+
    +
  • +

    Make it valid to pass non-variadic templates to the exposition-only alias +template gather-signatures, fixing the definitions of value_types_of_t, error_types_of_t, and the exposition-only alias +template sync-wait-type.

    +
  • +

    Removed the query forwarding from receiver_adaptor that was +inadvertantly left over from a previous edit.

    +
  • +

    When adapting a sender to an awaitable with as_awaitable, the sender’s +value result datum is decayed before being stored in the exposition-only variant.

    +
  • +

    Correctly specify the completion signatures of the schedule_from algorithm.

    +
  • +

    The sender_of concept no longer distinguishes between a sender of a +type T and a sender of a type T&&.

    +
  • +

    The just and just_error sender factories now reject C-style arrays +instead of silently decaying them to pointers.

    +
+

Enhancements:

+
    +
  • +

    The sender and receiver concepts get explicit opt-in traits called enable_sender and enable_receiver, respectively. The traits have +default implementations that look for nested is_sender and is_receiver types, respectively.

    +
  • +

    get_attrs is removed and get_env is used in its place.

    +
  • +

    The exposition-only type empty-env is made normative +and is renamed empty_env.

    +
  • +

    get_env gets a fall-back implementation that simply returns empty_env{} if a tag_invoke overload is not found.

    +
  • +

    get_env is required to be insensitive to the cvref-qualification of its +argument.

    +
  • +

    get_env, empty_env, and env_of_t are moved into the std:: namespace.

    +
  • +

    Add a new subclause describing the async programming model of senders in +abstract terms. See § 11.3 Asynchronous operations [async.ops].

    +
+

2.3. R6

+

The changes since R5 are as follows:

+

Fixes:

+
    +
  • +

    Fix typo in the specification of in_place_stop_source about the relative +lifetimes of the tokens and the source that produced them.

    +
  • +

    get_completion_signatures tests for awaitability with a promise type +similar to the one used by connect for the sake of consistency.

    +
  • +

    A coroutine promise type is an environment provider (that is, it implements get_env()) rather than being directly queryable. The previous draft was +inconsistent about that.

    +
+

Enhancements:

+
    +
  • +

    Sender queries are moved into a separate queryable "attributes" object +that is accessed by passing the sender to get_attrs() (see below). The sender concept is reexpressed to require get_attrs() and separated +from a new sender_in<Snd, Env> concept for checking whether a type is +a sender within a particular execution environment.

    +
  • +

    The placeholder types no_env and dependent_completion_signatures<> are no longer needed and are dropped.

    +
  • +

    ensure_started and split are changed to persist the result of +calling get_attrs() on the input sender.

    +
  • +

    Reorder constraints of the scheduler and receiver concepts to avoid constraint recursion +when used in tandem with poorly-constrained, implicitly convertible types.

    +
  • +

    Re-express the sender_of concept to be more ergonomic and general.

    +
  • +

    Make the specification of the alias templates value_types_of_t and error_types_of_t, and the variable template sends_done more concise by +expressing them in terms of a new exposition-only alias template gather-signatures.

    +
+

2.3.1. Environments and attributes

+

In earlier revisions, receivers, senders, and schedulers all were directly +queryable. In R4, receiver queries were moved into a separate "environment" +object, obtainable from a receiver with a get_env accessor. In R6, the +sender queries are given similar treatment, relocating to a "attributes" +object obtainable from a sender with a get_attrs accessor. This was done +to solve a number of design problems with the split and ensure_started algorithms; _e.g._, see NVIDIA/stdexec#466.

+

Schedulers, however, remain directly queryable. As lightweight handles +that are required to be movable and copyable, there is little reason to +want to dispose of a scheduler and yet persist the scheduler’s queries.

+

This revision also makes operation states directly queryable, even though +there isn’t yet a use for such. Some early prototypes of cooperative bulk +parallel sender algorithms done at NVIDIA suggest the utility of +forwardable operation state queries. The authors chose to make opstates +directly queryable since the opstate object is itself required to be kept +alive for the duration of asynchronous operation.

+

2.4. R5

+

The changes since R4 are as follows:

+

Fixes:

+
    +
  • +

    start_detached requires its argument to be a void sender (sends no values +to set_value).

    +
+

Enhancements:

+
    +
  • +

    Receiver concepts refactored to no longer require an error channel for exception_ptr or a stopped channel.

    +
  • +

    sender_of concept and connect customization point additionally require +that the receiver is capable of receiving all of the sender’s possible +completions.

    +
  • +

    get_completion_signatures is now required to return an instance of either completion_signatures or dependent_completion_signatures.

    +
  • +

    make_completion_signatures made more general.

    +
  • +

    receiver_adaptor handles get_env as it does the set_* members; that is, receiver_adaptor will look for a member named get_env() in the derived +class, and if found dispatch the get_env_t tag invoke customization to it.

    +
  • +

    just, just_error, just_stopped, and into_variant have been respecified +as customization point objects instead of functions, following LEWG guidance.

    +
+

2.5. R4

+

The changes since R3 are as follows:

+

Fixes:

+
    +
  • +

    Fix specification of get_completion_scheduler on the transfer, schedule_from and transfer_when_all algorithms; the completion scheduler cannot be guaranteed +for set_error.

    +
  • +

    The value of sends_stopped for the default sender traits of types that are +generally awaitable was changed from false to true to acknowledge the +fact that some coroutine types are generally awaitable and may implement the unhandled_stopped() protocol in their promise types.

    +
  • +

    Fix the incorrect use of inline namespaces in the <execution> header.

    +
  • +

    Shorten the stable names for the sections.

    +
  • +

    sync_wait now handles std::error_code specially by throwing a std::system_error on failure.

    +
  • +

    Fix how ADL isolation from class template arguments is specified so it +doesn’t constrain implmentations.

    +
  • +

    Properly expose the tag types in the header <execution> synopsis.

    +
+

Enhancements:

+
    +
  • +

    Support for "dependently-typed" senders, where the completion signatures -- and +thus the sender metadata -- depend on the type of the receiver connected +to it. See the section dependently-typed +senders below for more information.

    +
  • +

    Add a read(query) sender factory for issuing a query +against a receiver and sending the result through the value channel. (This is +a useful instance of a dependently-typed sender.)

    +
  • +

    Add completion_signatures utility for declaratively defining a typed +sender’s metadata.

    +
  • +

    Add make_completion_signatures utility for specifying a sender’s completion +signatures by adapting those of another sender.

    +
  • +

    Drop support for untyped senders and rename typed_sender to sender.

    +
  • +

    set_done is renamed to set_stopped. All occurances of "done" in +indentifiers replaced with "stopped"

    +
  • +

    Add customization points for controlling the forwarding of scheduler, +sender, receiver, and environment queries through layers of adaptors; +specify the behavior of the standard adaptors in terms of the new +customization points.

    +
  • +

    Add get_delegatee_scheduler query to forward a scheduler that can be used +by algorithms or by the scheduler to delegate work and forward progress.

    +
  • +

    Add schedule_result_t alias template.

    +
  • +

    More precisely specify the sender algorithms, including precisely what their +completion signatures are.

    +
  • +

    stopped_as_error respecified as a customization point object.

    +
  • +

    tag_invoke respecified to improve diagnostics.

    +
+

2.5.1. Dependently-typed senders

+

Background:

+

In the sender/receiver model, as with coroutines, contextual information about +the current execution is most naturally propagated from the consumer to the +producer. In coroutines, that means information like stop tokens, allocators and +schedulers are propagated from the calling coroutine to the callee. In +sender/receiver, that means that that contextual information is associated with +the receiver and is queried by the sender and/or operation state after the +sender and the receiver are connect-ed.

+

Problem:

+

The implication of the above is that the sender alone does not have all the +information about the async computation it will ultimately initiate; some of +that information is provided late via the receiver. However, the sender_traits mechanism, by which an algorithm can introspect the value and error types the +sender will propagate, only accepts a sender parameter. It does not take into +consideration the type information that will come in late via the receiver. The +effect of this is that some senders cannot be typed senders when they +otherwise could be.

+

Example:

+

To get concrete, consider the case of the "get_scheduler()" sender: when connect-ed and start-ed, it queries the receiver for its associated +scheduler and passes it back to the receiver through the value channel. That +sender’s "value type" is the type of the receiver’s scheduler. What then +should sender_traits<get_scheduler_sender>::value_types report for the get_scheduler()'s value type? It can’t answer because it doesn’t know.

+

This causes knock-on problems since some important algorithms require a typed +sender, such as sync_wait. To illustrate the problem, consider the following +code:

+
namespace ex = std::execution;
+
+ex::sender auto task =
+  ex::let_value(
+    ex::get_scheduler(), // Fetches scheduler from receiver.
+    [](auto current_sched) {
+      // Lauch some nested work on the current scheduler:
+      return ex::on(current_sched, nested work...);
+    });
+
+std::this_thread::sync_wait(std::move(task));
+
+

The code above is attempting to schedule some work onto the sync_wait's run_loop execution resource. But let_value only returns a typed sender when +the input sender is typed. As we explained above, get_scheduler() is not +typed, so task is likewise not typed. Since task isn’t typed, it cannot be +passed to sync_wait which is expecting a typed sender. The above code would +fail to compile.

+

Solution:

+

The solution is conceptually quite simple: extend the sender_traits mechanism +to optionally accept a receiver in addition to the sender. The algorithms can +use sender_traits<Sender, Receiver> to inspect the +async operation’s completion-signals. The typed_sender concept would also need +to take an optional receiver parameter. This is the simplest change, and it +would solve the immediate problem.

+

Design:

+

Using the receiver type to compute the sender traits turns out to have pitfalls +in practice. Many receivers make use of that type information in their +implementation. It is very easy to create cycles in the type system, leading to +inscrutible errors. The design pursued in R4 is to give receivers an associated environment object -- a bag of key/value pairs -- and to move the contextual +information (schedulers, etc) out of the receiver and into the environment. The sender_traits template and the typed_sender concept, rather than taking a +receiver, take an environment. This is a much more robust design.

+

A further refinement of this design would be to separate the receiver and the +environment entirely, passing then as separate arguments along with the sender to connect. This paper does not propose that change.

+

Impact:

+

This change, apart from increasing the expressive power of the sender/receiver abstraction, has the following impact:

+
    +
  • +

    Typed senders become moderately more challenging to write. (The new completion_signatures and transform_completion_signatures utilities are added +to ease this extra burden.)

    +
  • +

    Sender adaptor algorithms that previously constrained their sender arguments +to satisfy the typed_sender concept can no longer do so as the receiver is +not available yet. This can result in type-checking that is done later, when connect is ultimately called on the resulting sender adaptor.

    +
  • +

    Operation states that own receivers that add to or change the environment +are typically larger by one pointer. It comes with the benefit of far fewer +indirections to evaluate queries.

    +
+

"Has it been implemented?"

+

Yes, the reference implementation, which can be found at +https://github.com/NVIDIA/stdexec, has implemented this +design as well as some dependently-typed senders to confirm that it works.

+

Implementation experience

+

Although this change has not yet been made in libunifex, the most widely adopted sender/receiver implementation, a similar design can be found in Folly’s coroutine support library. In Folly.Coro, it is possible to await a special awaitable to obtain the current coroutine’s associated scheduler (called an executor in Folly).

+

For instance, the following Folly code grabs the current executor, schedules a task for execution on that executor, and starts the resulting (scheduled) task by enqueueing it for execution.

+
// From Facebook’s Folly open source library:
+template <class T>
+folly::coro::Task<void> CancellableAsyncScope::co_schedule(folly::coro::Task<T>&& task) {
+  this->add(std::move(task).scheduleOn(co_await co_current_executor));
+  co_return;
+}
+
+

Facebook relies heavily on this pattern in its coroutine code. But as described +above, this pattern doesn’t work with R3 of std::execution because of the lack +of dependently-typed schedulers. The change to sender_traits in R4 rectifies that.

+

Why now?

+

The authors are loathe to make any changes to the design, however small, at this +stage of the C++23 release cycle. But we feel that, for a relatively minor +design change -- adding an extra template parameter to sender_traits and typed_sender -- the returns are large enough to justify the change. And there +is no better time to make this change than as early as possible.

+

One might wonder why this missing feature not been added to sender/receiver +before now. The designers of sender/receiver have long been aware of the need. +What was missing was a clean, robust, and simple design for the change, which we +now have.

+

Drive-by:

+

We took the opportunity to make an additional drive-by change: Rather than +providing the sender traits via a class template for users to specialize, we +changed it into a sender query: get_completion_signatures(sender, env). That function’s return type is used as the sender’s traits. +The authors feel this leads to a more uniform design and gives sender authors a +straightforward way to make the value/error types dependent on the cv- and +ref-qualification of the sender if need be.

+

Details:

+

Below are the salient parts of the new support for dependently-typed senders in +R4:

+
    +
  • +

    Receiver queries have been moved from the receiver into a separate environment +object.

    +
  • +

    Receivers have an associated environment. The new get_env CPO retrieves a +receiver’s environment. If a receiver doesn’t implement get_env, it returns +an unspecified "empty" environment -- an empty struct.

    +
  • +

    sender_traits now takes an optional Env parameter that is used to +determine the error/value types.

    +
  • +

    The primary sender_traits template is replaced with a completion_signatures_of_t alias implemented in terms of a new get_completion_signatures CPO that dispatches +with tag_invoke. get_completion_signatures takes a sender and an optional +environment. A sender can customize this to specify its value/error types.

    +
  • +

    Support for untyped senders is dropped. The typed_sender concept has been +renamed to sender and now takes an optional environment.

    +
  • +

    The environment argument to the sender concept and the get_completion_signatures CPO defaults to no_env. All environment queries fail (are ill-formed) when +passed an instance of no_env.

    +
  • +

    A type S is required to satisfy sender<S> to be +considered a sender. If it doesn’t know what types it will complete with +independent of an environment, it returns an instance of the placeholder +traits dependent_completion_signatures.

    +
  • +

    If a sender satisfies both sender<S> and sender<S, Env>, then the completion signatures +for the two cannot be different in any way. It is possible for an +implementation to enforce this statically, but not required.

    +
  • +

    All of the algorithms and examples have been updated to work with +dependently-typed senders.

    +
+

2.6. R3

+

The changes since R2 are as follows:

+

Fixes:

+
    +
  • +

    Fix specification of the on algorithm to clarify lifetimes of +intermediate operation states and properly scope the get_scheduler query.

    +
  • +

    Fix a memory safety bug in the implementation of connect-awaitable.

    +
  • +

    Fix recursive definition of the scheduler concept.

    +
+

Enhancements:

+
    +
  • +

    Add run_loop execution resource.

    +
  • +

    Add receiver_adaptor utility to simplify writing receivers.

    +
  • +

    Require a scheduler’s sender to model sender_of and provide a completion scheduler.

    +
  • +

    Specify the cancellation scope of the when_all algorithm.

    +
  • +

    Make as_awaitable a customization point.

    +
  • +

    Change connect's handling of awaitables to consider those types that are awaitable owing to customization of as_awaitable.

    +
  • +

    Add value_types_of_t and error_types_of_t alias templates; rename stop_token_type_t to stop_token_of_t.

    +
  • +

    Add a design rationale for the removal of the possibly eager algorithms.

    +
  • +

    Expand the section on field experience.

    +
+

2.7. R2

+

The changes since R1 are as follows:

+
    +
  • +

    Remove the eagerly executing sender algorithms.

    +
  • +

    Extend the execution::connect customization point and the sender_traits<> template to recognize awaitables as typed_senders.

    +
  • +

    Add utilities as_awaitable() and with_awaitable_senders<> so a coroutine type can trivially make senders awaitable with a coroutine.

    +
  • +

    Add a section describing the design of the sender/awaitable interactions.

    +
  • +

    Add a section describing the design of the cancellation support in sender/receiver.

    +
  • +

    Add a section showing examples of simple sender adaptor algorithms.

    +
  • +

    Add a section showing examples of simple schedulers.

    +
  • +

    Add a few more examples: a sudoku solver, a parallel recursive file copy, and an echo server.

    +
  • +

    Refined the forward progress guarantees on the bulk algorithm.

    +
  • +

    Add a section describing how to use a range of senders to represent async sequences.

    +
  • +

    Add a section showing how to use senders to represent partial success.

    +
  • +

    Add sender factories execution::just_error and execution::just_stopped.

    +
  • +

    Add sender adaptors execution::stopped_as_optional and execution::stopped_as_error.

    +
  • +

    Document more production uses of sender/receiver at scale.

    +
  • +

    Various fixes of typos and bugs.

    +
+

2.8. R1

+

The changes since R0 are as follows:

+
    +
  • +

    Added a new concept, sender_of.

    +
  • +

    Added a new scheduler query, this_thread::execute_may_block_caller.

    +
  • +

    Added a new scheduler query, get_forward_progress_guarantee.

    +
  • +

    Removed the unschedule adaptor.

    +
  • +

    Various fixes of typos and bugs.

    +
+

2.9. R0

+

Initial revision.

+

3. Design - introduction

+

The following three sections describe the entirety of the proposed design.

+
    +
  • +

    § 3 Design - introduction describes the conventions used through the rest of the +design sections, as well as an example illustrating how we envision code will +be written using this proposal.

    +
  • +

    § 4 Design - user side describes all the functionality from the perspective we +intend for users: it describes the various concepts they will interact with, +and what their programming model is.

    +
  • +

    § 5 Design - implementer side describes the machinery that allows for that +programming model to function, and the information contained there is +necessary for people implementing senders and sender algorithms (including the +standard library ones) - but is not necessary to use senders productively.

    +
+

3.1. Conventions

+

The following conventions are used throughout the design section:

+
    +
  1. +

    The namespace proposed in this paper is the same as in A Unified Executors Proposal for C++: std::execution; however, for brevity, the std:: part of this name is + omitted. When you see execution::foo, treat that as std::execution::foo.

    +
  2. +

    Universal references and explicit calls to std::move/std::forward are + omitted in code samples and signatures for simplicity; assume universal + references and perfect forwarding unless stated otherwise.

    +
  3. +

    None of the names proposed here are names that we are particularly attached + to; consider the names to be reasonable placeholders that can freely be + changed, should the committee want to do so.

    +
+

3.2. Queries and algorithms

+

A query is a callable that takes some set of objects (usually one) as +parameters and returns facts about those objects without modifying them. Queries +are usually customization point objects, but in some cases may be functions.

+

An algorithm is a callable that takes some set of objects as parameters and +causes those objects to do something. Algorithms are usually customization point +objects, but in some cases may be functions.

+

4. Design - user side

+

4.1. Execution resources describe the place of execution

+

An execution resource is a resource that represents the place where +execution will happen. This could be a concrete resource - like a specific +thread pool object, or a GPU - or a more abstract one, like the current thread +of execution. Execution contexts don’t need to have a representation in code; +they are simply a term describing certain properties of execution of a function.

+

4.2. Schedulers represent execution resources

+

A scheduler is a lightweight handle that represents a strategy for +scheduling work onto an execution resource. Since execution resources don’t +necessarily manifest in C++ code, it’s not possible to program directly against +their API. A scheduler is a solution to that problem: the scheduler concept is +defined by a single sender algorithm, schedule, which returns a sender that +will complete on an execution resource determined by the scheduler. Logic that +you want to run on that context can be placed in the receiver’s +completion-signalling method.

+
execution::scheduler auto sch = thread_pool.scheduler();
+execution::sender auto snd = execution::schedule(sch);
+// snd is a sender (see below) describing the creation of a new execution resource
+// on the execution resource associated with sch
+
+

Note that a particular scheduler type may provide other kinds of scheduling operations +which are supported by its associated execution resource. It is not limited to scheduling +purely using the execution::schedule API.

+

Future papers will propose additional scheduler concepts that extend scheduler to add other capabilities. For example:

+
    +
  • +

    A time_scheduler concept that extends scheduler to support time-based +scheduling. Such a concept might provide access to schedule_after(sched, duration), schedule_at(sched, time_point) and now(sched) APIs.

    +
  • +

    Concepts that extend scheduler to support opening, reading and writing files +asynchronously.

    +
  • +

    Concepts that extend scheduler to support connecting, sending data and +receiving data over the network asynchronously.

    +
+

4.3. Senders describe work

+

A sender is an object that describes work. Senders are similar to futures in +existing asynchrony designs, but unlike futures, the work that is being done to +arrive at the values they will send is also directly described by the sender +object itself. A sender is said to send some values if a receiver connected +(see § 5.3 execution::connect) to that sender will eventually receive said values.

+

The primary defining sender algorithm is § 5.3 execution::connect; this function, +however, is not a user-facing API; it is used to facilitate communication +between senders and various sender algorithms, but end user code is not expected +to invoke it directly.

+

The way user code is expected to interact with senders is by using sender +algorithms. This paper proposes an initial set of such sender algorithms, +which are described in § 4.4 Senders are composable through sender algorithms, § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers. For example, here +is how a user can create a new sender on a scheduler, attach a continuation to +it, and then wait for execution of the continuation to complete:

+
execution::scheduler auto sch = thread_pool.scheduler();
+execution::sender auto snd = execution::schedule(sch);
+execution::sender auto cont = execution::then(snd, []{
+    std::fstream file{ "result.txt" };
+    file << compute_result;
+});
+
+this_thread::sync_wait(cont);
+// at this point, cont has completed execution
+
+

4.4. Senders are composable through sender algorithms

+

Asynchronous programming often departs from traditional code structure and control flow that we are familiar with. +A successful asynchronous framework must provide an intuitive story for composition of asynchronous work: expressing dependencies, passing objects, managing object lifetimes, etc.

+

The true power and utility of senders is in their composability. +With senders, users can describe generic execution pipelines and graphs, and then run them on and across a variety of different schedulers. +Senders are composed using sender algorithms:

+
    +
  • +

    sender factories, algorithms that take no senders and return a sender.

    +
  • +

    sender adaptors, algorithms that take (and potentially execution::connect) senders and return a sender.

    +
  • +

    sender consumers, algorithms that take (and potentially execution::connect) senders and do not return a sender.

    +
+

4.5. Senders can propagate completion schedulers

+

One of the goals of executors is to support a diverse set of execution resources, including traditional thread pools, task and fiber frameworks (like HPX and Legion), and GPUs and other accelerators (managed by runtimes such as CUDA or SYCL). +On many of these systems, not all execution agents are created equal and not all functions can be run on all execution agents. +Having precise control over the execution resource used for any given function call being submitted is important on such systems, and the users of standard execution facilities will expect to be able to express such requirements.

+

A Unified Executors Proposal for C++ was not always clear about the place of execution of any given piece of code. +Precise control was present in the two-way execution API present in earlier executor designs, but it has so far been missing from the senders design. There has been a proposal (Towards C++23 executors: A proposal for an initial set of algorithms) to provide a number of sender algorithms that would enforce certain rules on the places of execution +of the work described by a sender, but we have found those sender algorithms to be insufficient for achieving the best performance on all platforms that are of interest to us. The implementation strategies that we are aware of result in one of the following situations:

+
    +
  1. +

    trying to submit work to one execution resource (such as a CPU thread pool) from another execution resource (such as a GPU or a task framework), which assumes that all execution agents are as capable as a std::thread (which they aren’t).

    +
  2. +

    forcibly interleaving two adjacent execution graph nodes that are both executing on one execution resource (such as a GPU) with glue code that runs on another execution resource (such as a CPU), which is prohibitively expensive for some execution resources (such as CUDA or SYCL).

    +
  3. +

    having to customise most or all sender algorithms to support an execution resource, so that you can avoid problems described in 1. and 2, which we believe is impractical and brittle based on months of field experience attempting this in Agency.

    +
+

None of these implementation strategies are acceptable for many classes of parallel runtimes, such as task frameworks (like HPX) or accelerator runtimes (like CUDA or SYCL).

+

Therefore, in addition to the on sender algorithm from Towards C++23 executors: A proposal for an initial set of algorithms, we are proposing a way for senders to advertise what scheduler (and by extension what execution resource) they will complete on. +Any given sender may have completion schedulers for some or all of the signals (value, error, or stopped) it completes with (for more detail on the completion-signals, see § 5.1 Receivers serve as glue between senders). +When further work is attached to that sender by invoking sender algorithms, that work will also complete on an appropriate completion scheduler.

+

4.5.1. execution::get_completion_scheduler

+

get_completion_scheduler is a query that retrieves the completion scheduler for a specific completion-signal from a sender’s environment. +For a sender that lacks a completion scheduler query for a given signal, calling get_completion_scheduler is ill-formed. +If a sender advertises a completion scheduler for a signal in this way, that sender must ensure that it sends that signal on an execution agent belonging to an execution resource represented by a scheduler returned from this function. +See § 4.5 Senders can propagate completion schedulers for more details.

+
execution::scheduler auto cpu_sched = new_thread_scheduler{};
+execution::scheduler auto gpu_sched = cuda::scheduler();
+
+execution::sender auto snd0 = execution::schedule(cpu_sched);
+execution::scheduler auto completion_sch0 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd0));
+// completion_sch0 is equivalent to cpu_sched
+
+execution::sender auto snd1 = execution::then(snd0, []{
+    std::cout << "I am running on cpu_sched!\n";
+});
+execution::scheduler auto completion_sch1 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd1));
+// completion_sch1 is equivalent to cpu_sched
+
+execution::sender auto snd2 = execution::transfer(snd1, gpu_sched);
+execution::sender auto snd3 = execution::then(snd2, []{
+    std::cout << "I am running on gpu_sched!\n";
+});
+execution::scheduler auto completion_sch3 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd3));
+// completion_sch3 is equivalent to gpu_sched
+
+

4.6. Execution resource transitions are explicit

+

A Unified Executors Proposal for C++ does not contain any mechanisms for performing an execution resource transition. The only sender algorithm that can create a sender that will move execution to a specific execution resource is execution::schedule, which does not take an input sender. +That means that there’s no way to construct sender chains that traverse different execution resources. This is necessary to fulfill the promise of senders being able to replace two-way executors, which had this capability.

+

We propose that, for senders advertising their completion scheduler, all execution resource transitions must be explicit; running user code anywhere but where they defined it to run must be considered a bug.

+

The execution::transfer sender adaptor performs a transition from one execution resource to another:

+
execution::scheduler auto sch1 = ...;
+execution::scheduler auto sch2 = ...;
+
+execution::sender auto snd1 = execution::schedule(sch1);
+execution::sender auto then1 = execution::then(snd1, []{
+    std::cout << "I am running on sch1!\n";
+});
+
+execution::sender auto snd2 = execution::transfer(then1, sch2);
+execution::sender auto then2 = execution::then(snd2, []{
+    std::cout << "I am running on sch2!\n";
+});
+
+this_thread::sync_wait(then2);
+
+

4.7. Senders can be either multi-shot or single-shot

+

Some senders may only support launching their operation a single time, while others may be repeatable +and support being launched multiple times. Executing the operation may consume resources owned by the +sender.

+

For example, a sender may contain a std::unique_ptr that it will be transferring ownership of to the +operation-state returned by a call to execution::connect so that the operation has access to +this resource. In such a sender, calling execution::connect consumes the sender such that after +the call the input sender is no longer valid. Such a sender will also typically be move-only so that +it can maintain unique ownership of that resource.

+

A single-shot sender can only be connected to a receiver +at most once. Its implementation of execution::connect only has overloads for +an rvalue-qualified sender. Callers must pass the sender as an rvalue to the +call to execution::connect, indicating that the call consumes the sender.

+

A multi-shot sender can be connected to multiple +receivers and can be launched multiple times. Multi-shot senders customise execution::connect to accept an lvalue reference to the sender. Callers can +indicate that they want the sender to remain valid after the call to execution::connect by passing an lvalue reference to the sender to call these +overloads. Multi-shot senders should also define overloads of execution::connect that accept rvalue-qualified senders to allow the sender to +be also used in places where only a single-shot sender is required.

+

If the user of a sender does not require the sender to remain valid after connecting it to a +receiver then it can pass an rvalue-reference to the sender to the call to execution::connect. +Such usages should be able to accept either single-shot or multi-shot senders.

+

If the caller does wish for the sender to remain valid after the call then it can pass an lvalue-qualified sender +to the call to execution::connect. Such usages will only accept multi-shot senders.

+

Algorithms that accept senders will typically either decay-copy an input sender and store it somewhere +for later usage (for example as a data-member of the returned sender) or will immediately call execution::connect on the input sender, such as in this_thread::sync_wait or execution::start_detached.

+

Some multi-use sender algorithms may require that an input sender be copy-constructible but will only call execution::connect on an rvalue of each copy, which still results in effectively executing the operation multiple times. +Other multi-use sender algorithms may require that the sender is move-constructible but will invoke execution::connect on an lvalue reference to the sender.

+

For a sender to be usable in both multi-use scenarios, it will generally be required to be both copy-constructible and lvalue-connectable.

+

4.8. Senders are forkable

+

Any non-trivial program will eventually want to fork a chain of senders into independent streams of work, regardless of whether they are single-shot or multi-shot. +For instance, an incoming event to a middleware system may be required to trigger events on more than one downstream system. +This requires that we provide well defined mechanisms for making sure that connecting a sender multiple times is possible and correct.

+

The split sender adaptor facilitates connecting to a sender multiple times, regardless of whether it is single-shot or multi-shot:

+
auto some_algorithm(execution::sender auto&& input) {
+    execution::sender auto multi_shot = split(input);
+    // "multi_shot" is guaranteed to be multi-shot,
+    // regardless of whether "input" was multi-shot or not
+
+    return when_all(
+      then(multi_shot, [] { std::cout << "First continuation\n"; }),
+      then(multi_shot, [] { std::cout << "Second continuation\n"; })
+    );
+}
+
+

4.9. Senders support cancellation

+

Senders are often used in scenarios where the application may be concurrently executing +multiple strategies for achieving some program goal. When one of these strategies succeeds +(or fails) it may not make sense to continue pursuing the other strategies as their results +are no longer useful.

+

For example, we may want to try to simultaneously connect to multiple network servers and use +whichever server responds first. Once the first server responds we no longer need to continue +trying to connect to the other servers.

+

Ideally, in these scenarios, we would somehow be able to request that those other strategies +stop executing promptly so that their resources (e.g. cpu, memory, I/O bandwidth) can be +released and used for other work.

+

While the design of senders has support for cancelling an operation before it starts +by simply destroying the sender or the operation-state returned from execution::connect() before calling execution::start(), there also needs to be a standard, generic mechanism +to ask for an already-started operation to complete early.

+

The ability to be able to cancel in-flight operations is fundamental to supporting some kinds +of generic concurrency algorithms.

+

For example:

+
    +
  • +

    a when_all(ops...) algorithm should cancel other operations as soon as one operation fails

    +
  • +

    a first_successful(ops...) algorithm should cancel the other operations as soon as one operation completes successfuly

    +
  • +

    a generic timeout(src, duration) algorithm needs to be able to cancel the src operation after the timeout duration has elapsed.

    +
  • +

    a stop_when(src, trigger) algorithm should cancel src if trigger completes first and cancel trigger if src completes first

    +
+

The mechanism used for communcating cancellation-requests, or stop-requests, needs to have a uniform interface +so that generic algorithms that compose sender-based operations, such as the ones listed above, are able to +communicate these cancellation requests to senders that they don’t know anything about.

+

The design is intended to be composable so that cancellation of higher-level operations can propagate +those cancellation requests through intermediate layers to lower-level operations that need to actually +respond to the cancellation requests.

+

For example, we can compose the algorithms mentioned above so that child operations +are cancelled when any one of the multiple cancellation conditions occurs:

+
sender auto composed_cancellation_example(auto query) {
+  return stop_when(
+    timeout(
+      when_all(
+        first_successful(
+          query_server_a(query),
+          query_server_b(query)),
+        load_file("some_file.jpg")),
+      5s),
+    cancelButton.on_click());
+}
+
+

In this example, if we take the operation returned by query_server_b(query), this operation will +receive a stop-request when any of the following happens:

+
    +
  • +

    first_successful algorithm will send a stop-request if query_server_a(query) completes successfully

    +
  • +

    when_all algorithm will send a stop-request if the load_file("some_file.jpg") operation completes with an error or stopped result.

    +
  • +

    timeout algorithm will send a stop-request if the operation does not complete within 5 seconds.

    +
  • +

    stop_when algorithm will send a stop-request if the user clicks on the "Cancel" button in the user-interface.

    +
  • +

    The parent operation consuming the composed_cancellation_example() sends a stop-request

    +
+

Note that within this code there is no explicit mention of cancellation, stop-tokens, callbacks, etc. +yet the example fully supports and responds to the various cancellation sources.

+

The intent of the design is that the common usage of cancellation in sender/receiver-based code is +primarily through use of concurrency algorithms that manage the detailed plumbing of cancellation +for you. Much like algorithms that compose senders relieve the user from having to write their own +receiver types, algorithms that introduce concurrency and provide higher-level cancellation semantics +relieve the user from having to deal with low-level details of cancellation.

+

4.9.1. Cancellation design summary

+

The design of cancellation described in this paper is built on top of and extends the std::stop_token-based +cancellation facilities added in C++20, first proposed in Composable cancellation for sender-based async operations.

+

At a high-level, the facilities proposed by this paper for supporting cancellation include:

+
    +
  • +

    Add std::stoppable_token and std::stoppable_token_for concepts that generalise the interface of std::stop_token type to allow other types with different implementation strategies.

    +
  • +

    Add std::unstoppable_token concept for detecting whether a stoppable_token can never receive a stop-request.

    +
  • +

    Add std::in_place_stop_token, std::in_place_stop_source and std::in_place_stop_callback<CB> types that provide a more efficient implementation of a stop-token for use in structured concurrency situations.

    +
  • +

    Add std::never_stop_token for use in places where you never want to issue a stop-request

    +
  • +

    Add std::execution::get_stop_token() CPO for querying the stop-token to use for an operation from its receiver’s execution environment.

    +
  • +

    Add std::execution::stop_token_of_t<T> for querying the type of a stop-token returned from get_stop_token()

    +
+

In addition, there are requirements added to some of the algorithms to specify what their cancellation +behaviour is and what the requirements of customisations of those algorithms are with respect to +cancellation.

+

The key component that enables generic cancellation within sender-based operations is the execution::get_stop_token() CPO. +This CPO takes a single parameter, which is the execution environment of the receiver passed to execution::connect, and returns a std::stoppable_token that the operation can use to check for stop-requests for that operation.

+

As the caller of execution::connect typically has control over the receiver +type it passes, it is able to customise the std::execution::get_env() CPO for that +receiver to return an execution environment that hooks the execution::get_stop_token() CPO to return a stop-token that the receiver has +control over and that it can use to communicate a stop-request to the operation +once it has started.

+

4.9.2. Support for cancellation is optional

+

Support for cancellation is optional, both on part of the author of the receiver and on part of the author of the sender.

+

If the receiver’s execution environment does not customise the execution::get_stop_token() CPO then invoking the CPO on that receiver’s +environment will invoke the default implementation which returns std::never_stop_token. This is a special stoppable_token type that is +statically known to always return false from the stop_possible() method.

+

Sender code that tries to use this stop-token will in general result in code that handles stop-requests being +compiled out and having little to no run-time overhead.

+

If the sender doesn’t call execution::get_stop_token(), for example because the operation does not support +cancellation, then it will simply not respond to stop-requests from the caller.

+

Note that stop-requests are generally racy in nature as there is often a race betwen an operation completing +naturally and the stop-request being made. If the operation has already completed or past the point at which +it can be cancelled when the stop-request is sent then the stop-request may just be ignored. An application +will typically need to be able to cope with senders that might ignore a stop-request anyway.

+

4.9.3. Cancellation is inherently racy

+

Usually, an operation will attach a stop-callback at some point inside the call to execution::start() so that +a subsequent stop-request will interrupt the logic.

+

A stop-request can be issued concurrently from another thread. This means the implementation of execution::start() needs to be careful to ensure that, once a stop-callback has been registered, that there are no data-races between +a potentially concurrently-executing stop-callback and the rest of the execution::start() implementation.

+

An implementation of execution::start() that supports cancellation will generally need to perform (at least) +two separate steps: launch the operation, subscribe a stop-callback to the receiver’s stop-token. Care needs +to be taken depending on the order in which these two steps are performed.

+

If the stop-callback is subscribed first and then the operation is launched, care needs to be taken to ensure +that a stop-request that invokes the stop-callback on another thread after the stop-callback is registered +but before the operation finishes launching does not either result in a missed cancellation request or a +data-race. e.g. by performing an atomic write after the launch has finished executing

+

If the operation is launched first and then the stop-callback is subscribed, care needs to be taken to ensure +that if the launched operation completes concurrently on another thread that it does not destroy the operation-state +until after the stop-callback has been registered. e.g. by having the execution::start implementation write to +an atomic variable once it has finished registering the stop-callback and having the concurrent completion handler +check that variable and either call the completion-signalling operation or store the result and defer calling the +receiver’s completion-signalling operation to the execution::start() call (which is still executing).

+

For an example of an implementation strategy for solving these data-races see § 1.4 Asynchronous Windows socket recv.

+

4.9.4. Cancellation design status

+

This paper currently includes the design for cancellation as proposed in Composable cancellation for sender-based async operations - "Composable cancellation for sender-based async operations". +P2175R0 contains more details on the background motivation and prior-art and design rationale of this design.

+

It is important to note, however, that initial review of this design in the SG1 concurrency subgroup raised some concerns +related to runtime overhead of the design in single-threaded scenarios and these concerns are still being investigated.

+

The design of P2175R0 has been included in this paper for now, despite its potential to change, as we believe that +support for cancellation is a fundamental requirement for an async model and is required in some form to be able to +talk about the semantics of some of the algorithms proposed in this paper.

+

This paper will be updated in the future with any changes that arise from the investigations into P2175R0.

+

4.10. Sender factories and adaptors are lazy

+

In an earlier revision of this paper, some of the proposed algorithms supported +executing their logic eagerly; i.e., before the returned sender has been +connected to a receiver and started. These algorithms were removed because eager +execution has a number of negative semantic and performance implications.

+

We have originally included this functionality in the paper because of a long-standing +belief that eager execution is a mandatory feature to be included in the standard Executors +facility for that facility to be acceptable for accelerator vendors. A particular concern +was that we must be able to write generic algorithms that can run either eagerly or lazily, +depending on the kind of an input sender or scheduler that have been passed into them as +arguments. We considered this a requirement, because the _latency_ of launching work on an +accelerator can sometimes be considerable.

+

However, in the process of working on this paper and implementations of the features +proposed within, our set of requirements has shifted, as we understood the different +implementation strategies that are available for the feature set of this paper better, +and, after weighting the earlier concerns against the points presented below, we +have arrived at the conclusion that a purely lazy model is enough for most algorithms, +and users who intend to launch work earlier may use an algorithm such as ensure_started to achieve that goal. We have also come to deeply appreciate the fact that a purely +lazy model allows both the implementation and the compiler to have a much better +understanding of what the complete graph of tasks looks like, allowing them to better +optimize the code - also when targetting accelerators.

+

4.10.1. Eager execution leads to detached work or worse

+

One of the questions that arises with APIs that can potentially return +eagerly-executing senders is "What happens when those senders are destructed +without a call to execution::connect?" or similarly, "What happens if a call +to execution::connect is made, but the returned operation state is destroyed +before execution::start is called on that operation state"?

+

In these cases, the operation represented by the sender is potentially executing +concurrently in another thread at the time that the destructor of the sender +and/or operation-state is running. In the case that the operation has not +completed executing by the time that the destructor is run we need to decide +what the semantics of the destructor is.

+

There are three main strategies that can be adopted here, none of which is +particularly satisfactory:

+
    +
  1. +

    Make this undefined-behaviour - the caller must ensure that any +eagerly-executing sender is always joined by connecting and starting that +sender. This approach is generally pretty hostile to programmers, +particularly in the presence of exceptions, since it complicates the ability +to compose these operations.

    +

    Eager operations typically need to acquire resources when they are first +called in order to start the operation early. This makes eager algorithms +prone to failure. Consider, then, what might happen in an expression such as when_all(eager_op_1(), eager_op_2()). Imagine eager_op_1() starts an +asynchronous operation successfully, but then eager_op_2() throws. For +lazy senders, that failure happens in the context of the when_all algorithm, which handles the failure and ensures that async work joins on +all code paths. In this case though -- the eager case -- the child operation +has failed even before when_all has been called.

    +

    It then becomes the responsibility, not of the algorithm, but of the end +user to handle the exception and ensure that eager_op_1() is joined before +allowing the exception to propagate. If they fail to do that, they incur +undefined behavior.

    +
  2. +

    Detach from the computation - let the operation continue in the background - +like an implicit call to std::thread::detach(). While this approach can +work in some circumstances for some kinds of applications, in general it is +also pretty user-hostile; it makes it difficult to reason about the safe +destruction of resources used by these eager operations. In general, +detached work necessitates some kind of garbage collection; e.g., std::shared_ptr, to ensure resources are kept alive until the operations +complete, and can make clean shutdown nigh impossible.

    +
  3. +

    Block in the destructor until the operation completes. This approach is +probably the safest to use as it preserves the structured nature of the +concurrent operations, but also introduces the potential for deadlocking the +application if the completion of the operation depends on the current thread +making forward progress.

    +

    The risk of deadlock might occur, for example, if a thread-pool with a +small number of threads is executing code that creates a sender representing +an eagerly-executing operation and then calls the destructor of that sender +without joining it (e.g. because an exception was thrown). If the current +thread blocks waiting for that eager operation to complete and that eager +operation cannot complete until some entry enqueued to the thread-pool’s +queue of work is run then the thread may wait for an indefinite amount of +time. If all threads of the thread-pool are simultaneously performing such +blocking operations then deadlock can result.

    +
+

There are also minor variations on each of these choices. For example:

+
    +
  1. +

    A variation of (1): Call std::terminate if an eager sender is destructed +without joining it. This is the approach that std::thread destructor +takes.

    +
  2. +

    A variation of (2): Request cancellation of the operation before detaching. +This reduces the chances of operations continuing to run indefinitely in the +background once they have been detached but does not solve the +lifetime- or shutdown-related challenges.

    +
  3. +

    A variation of (3): Request cancellation of the operation before blocking on +its completion. This is the strategy that std::jthread uses for its +destructor. It reduces the risk of deadlock but does not eliminate it.

    +
+

4.10.2. Eager senders complicate algorithm implementations

+

Algorithms that can assume they are operating on senders with strictly lazy +semantics are able to make certain optimizations that are not available if +senders can be potentially eager. With lazy senders, an algorithm can safely +assume that a call to execution::start on an operation state strictly happens +before the execution of that async operation. This frees the algorithm from +needing to resolve potential race conditions. For example, consider an algorithm sequence that puts async operations in sequence by starting an operation only +after the preceding one has completed. In an expression like sequence(a(), then(src, [] { b(); }), c()), one may reasonably assume that a(), b() and c() are sequenced and therefore do not need synchronisation. Eager algorithms +break that assumption.

+

When an algorithm needs to deal with potentially eager senders, the potential +race conditions can be resolved one of two ways, neither of which is desirable:

+
    +
  1. +

    Assume the worst and implement the algorithm defensively, assuming all +senders are eager. This obviously has overheads both at runtime and in +algorithm complexity. Resolving race conditions is hard.

    +
  2. +

    Require senders to declare whether they are eager or not with a query. +Algorithms can then implement two different implementation strategies, one +for strictly lazy senders and one for potentially eager senders. This +addresses the performance problem of (1) while compounding the complexity +problem.

    +
+

4.10.3. Eager senders incur cancellation-related overhead

+

Another implication of the use of eager operations is with regards to +cancellation. The eagerly executing operation will not have access to the +caller’s stop token until the sender is connected to a receiver. If we still +want to be able to cancel the eager operation then it will need to create a new +stop source and pass its associated stop token down to child operations. Then +when the returned sender is eventually connected it will register a stop +callback with the receiver’s stop token that will request stop on the eager +sender’s stop source.

+

As the eager operation does not know at the time that it is launched what the +type of the receiver is going to be, and thus whether or not the stop token +returned from execution::get_stop_token is an std::unstoppable_token or not, +the eager operation is going to need to assume it might be later connected to a +receiver with a stop token that might actually issue a stop request. Thus it +needs to declare space in the operation state for a type-erased stop callback +and incur the runtime overhead of supporting cancellation, even if cancellation +will never be requested by the caller.

+

The eager operation will also need to do this to support sending a stop request +to the eager operation in the case that the sender representing the eager work +is destroyed before it has been joined (assuming strategy (5) or (6) listed +above is chosen).

+

4.10.4. Eager senders cannot access execution resource from the receiver

+

In sender/receiver, contextual information is passed from parent operations to +their children by way of receivers. Information like stop tokens, allocators, +current scheduler, priority, and deadline are propagated to child operations +with custom receivers at the time the operation is connected. That way, each +operation has the contextual information it needs before it is started.

+

But if the operation is started before it is connected to a receiver, then there +isn’t a way for a parent operation to communicate contextual information to its +child operations, which may complete before a receiver is ever attached.

+

4.11. Schedulers advertise their forward progress guarantees

+

To decide whether a scheduler (and its associated execution resource) is sufficient for a specific task, it may be necessary to know what kind of forward progress guarantees it provides for the execution agents it creates. The C++ Standard defines the following +forward progress guarantees:

+
    +
  • +

    concurrent, which requires that a thread makes progress eventually;

    +
  • +

    parallel, which requires that a thread makes progress once it executes a step; and

    +
  • +

    weakly parallel, which does not require that the thread makes progress.

    +
+

This paper introduces a scheduler query function, get_forward_progress_guarantee, which returns one of the enumerators of a new enum type, forward_progress_guarantee. Each enumerator of forward_progress_guarantee corresponds to one of the aforementioned +guarantees.

+

4.12. Most sender adaptors are pipeable

+

To facilitate an intuitive syntax for composition, most sender adaptors are pipeable; they can be composed (piped) together with operator|. +This mechanism is similar to the operator| composition that C++ range adaptors support and draws inspiration from piping in *nix shells. +Pipeable sender adaptors take a sender as their first parameter and have no other sender parameters.

+

a | b will pass the sender a as the first argument to the pipeable sender adaptor b. Pipeable sender adaptors support partial application of the parameters after the first. For example, all of the following are equivalent:

+
execution::bulk(snd, N, [] (std::size_t i, auto d) {});
+execution::bulk(N, [] (std::size_t i, auto d) {})(snd);
+snd | execution::bulk(N, [] (std::size_t i, auto d) {});
+
+

Piping enables you to compose together senders with a linear syntax. +Without it, you’d have to use either nested function call syntax, which would cause a syntactic inversion of the direction of control flow, or you’d have to introduce a temporary variable for each stage of the pipeline. +Consider the following example where we want to execute first on a CPU thread pool, then on a CUDA GPU, then back on the CPU thread pool:

+ + + + + + +
Syntax Style + Example +
Function call
(nested) +
+
auto snd = execution::then(
+             execution::transfer(
+               execution::then(
+                 execution::transfer(
+                   execution::then(
+                     execution::schedule(thread_pool.scheduler())
+                     []{ return 123; }),
+                   cuda::new_stream_scheduler()),
+                 [](int i){ return 123 * 5; }),
+               thread_pool.scheduler()),
+             [](int i){ return i - 5; });
+auto [result] = this_thread::sync_wait(snd).value();
+// result == 610
+
+
Function call
(named temporaries) +
+
auto snd0 = execution::schedule(thread_pool.scheduler());
+auto snd1 = execution::then(snd0, []{ return 123; });
+auto snd2 = execution::transfer(snd1, cuda::new_stream_scheduler());
+auto snd3 = execution::then(snd2, [](int i){ return 123 * 5; })
+auto snd4 = execution::transfer(snd3, thread_pool.scheduler())
+auto snd5 = execution::then(snd4, [](int i){ return i - 5; });
+auto [result] = *this_thread::sync_wait(snd4);
+// result == 610
+
+
Pipe + +
auto snd = execution::schedule(thread_pool.scheduler())
+         | execution::then([]{ return 123; })
+         | execution::transfer(cuda::new_stream_scheduler())
+         | execution::then([](int i){ return 123 * 5; })
+         | execution::transfer(thread_pool.scheduler())
+         | execution::then([](int i){ return i - 5; });
+auto [result] = this_thread::sync_wait(snd).value();
+// result == 610
+
+
+

Certain sender adaptors are not pipeable, because using the pipeline syntax can result in confusion of the semantics of the adaptors involved. Specifically, the following sender adaptors are not pipeable.

+
    +
  • +

    execution::when_all and execution::when_all_with_variant: Since this sender adaptor takes a variadic pack of senders, a partially applied form would be ambiguous with a non partially applied form with an arity of one less.

    +
  • +

    execution::on: This sender adaptor changes how the sender passed to it is executed, not what happens to its result, but allowing it in a pipeline makes it read as if it performed a function more similar to transfer.

    +
+

Sender consumers could be made pipeable, but we have chosen to not do so. +However, since these are terminal nodes in a pipeline and nothing can be piped after them, we believe a pipe syntax may be confusing as well as unnecessary, as consumers cannot be chained. +We believe sender consumers read better with function call syntax.

+

4.13. A range of senders represents an async sequence of data

+

Senders represent a single unit of asynchronous work. In many cases though, what is being modelled is a sequence of data arriving asynchronously, and you want computation to happen on demand, when each element arrives. This requires nothing more than what is in this paper and the range support in C++20. A range of senders would allow you to model such input as keystrikes, mouse movements, sensor readings, or network requests.

+

Given some expression R that is a range of senders, consider the following in a coroutine that returns an async generator type:

+
for (auto snd : R) {
+  if (auto opt = co_await execution::stopped_as_optional(std::move(snd)))
+    co_yield fn(*std::move(opt));
+  else
+    break;
+}
+
+

This transforms each element of the asynchronous sequence R with the function fn on demand, as the data arrives. The result is a new asynchronous sequence of the transformed values.

+

Now imagine that R is the simple expression views::iota(0) | views::transform(execution::just). This creates a lazy range of senders, each of which completes immediately with monotonically increasing integers. The above code churns through the range, generating a new infine asynchronous range of values [fn(0), fn(1), fn(2), ...].

+

Far more interesting would be if R were a range of senders representing, say, user actions in a UI. The above code gives a simple way to respond to user actions on demand.

+

4.14. Senders can represent partial success

+

Receivers have three ways they can complete: with success, failure, or cancellation. This begs the question of how they can be used to represent async operations that partially succeed. For example, consider an API that reads from a socket. The connection could drop after the API has filled in some of the buffer. In cases like that, it makes sense to want to report both that the connection dropped and that some data has been successfully read.

+

Often in the case of partial success, the error condition is not fatal nor does it mean the API has failed to satisfy its post-conditions. It is merely an extra piece of information about the nature of the completion. In those cases, "partial success" is another way of saying "success". As a result, it is sensible to pass both the error code and the result (if any) through the value channel, as shown below:

+
// Capture a buffer for read_socket_async to fill in
+execution::just(array<byte, 1024>{})
+  | execution::let_value([socket](array<byte, 1024>& buff) {
+      // read_socket_async completes with two values: an error_code and
+      // a count of bytes:
+      return read_socket_async(socket, span{buff})
+          // For success (partial and full), specify the next action:
+        | execution::let_value([](error_code err, size_t bytes_read) {
+            if (err != 0) {
+              // OK, partial success. Decide how to deal with the partial results
+            } else {
+              // OK, full success here.
+            }
+          });
+    })
+
+

In other cases, the partial success is more of a partial failure. That happens when the error condition indicates that in some way the function failed to satisfy its post-conditions. In those cases, sending the error through the value channel loses valuable contextual information. It’s possible that bundling the error and the incomplete results into an object and passing it through the error channel makes more sense. In that way, generic algorithms will not miss the fact that a post-condition has not been met and react inappropriately.

+

Another possibility is for an async API to return a range of senders: if the API completes with full success, full error, or cancellation, the returned range contains just one sender with the result. Otherwise, if the API partially fails (doesn’t satisfy its post-conditions, but some incomplete result is available), the returned range would have two senders: the first containing the partial result, and the second containing the error. Such an API might be used in a coroutine as follows:

+
// Declare a buffer for read_socket_async to fill in
+array<byte, 1024> buff;
+
+for (auto snd : read_socket_async(socket, span{buff})) {
+  try {
+    if (optional<size_t> bytes_read =
+          co_await execution::stopped_as_optional(std::move(snd))) {
+      // OK, we read some bytes into buff. Process them here....
+    } else {
+      // The socket read was cancelled and returned no data. React
+      // appropriately.
+    }
+  } catch (...) {
+    // read_socket_async failed to meet its post-conditions.
+    // Do some cleanup and propagate the error...
+  }
+}
+
+

Finally, it’s possible to combine these two approaches when the API can both partially succeed (meeting its post-conditions) and partially fail (not meeting its post-conditions).

+

4.15. All awaitables are senders

+

Since C++20 added coroutines to the standard, we expect that coroutines and awaitables will be how a great many will choose to express their asynchronous code. However, in this paper, we are proposing to add a suite of asynchronous algorithms that accept senders, not awaitables. One might wonder whether and how these algorithms will be accessible to those who choose coroutines instead of senders.

+

In truth there will be no problem because all generally awaitable types +automatically model the sender concept. The adaptation is transparent and +happens in the sender customization points, which are aware of awaitables. (By +"generally awaitable" we mean types that don’t require custom await_transform trickery from a promise type to make them awaitable.)

+

For an example, imagine a coroutine type called task<T> that knows nothing +about senders. It doesn’t implement any of the sender customization points. +Despite that fact, and despite the fact that the this_thread::sync_wait algorithm is constrained with the sender concept, the following would compile +and do what the user wants:

+
task<int> doSomeAsyncWork();
+
+int main() {
+  // OK, awaitable types satisfy the requirements for senders:
+  auto o = this_thread::sync_wait(doSomeAsyncWork());
+}
+
+

Since awaitables are senders, writing a sender-based asynchronous algorithm is trivial if you have a coroutine task type: implement the algorithm as a coroutine. If you are not bothered by the possibility of allocations and indirections as a result of using coroutines, then there is no need to ever write a sender, a receiver, or an operation state.

+

4.16. Many senders can be trivially made awaitable

+

If you choose to implement your sender-based algorithms as coroutines, you’ll run into the issue of how to retrieve results from a passed-in sender. This is not a problem. If the coroutine type opts in to sender support -- trivial with the execution::with_awaitable_senders utility -- then a large class of senders are transparently awaitable from within the coroutine.

+

For example, consider the following trivial implementation of the sender-based retry algorithm:

+
template<class S>
+  requires single-sender<S&> // see [exec.as.awaitable]
+task<single-sender-value-type<S>> retry(S s) {
+  for (;;) {
+    try {
+      co_return co_await s;
+    } catch(...) {
+    }
+  }
+}
+
+

Only some senders can be made awaitable directly because of the fact that callbacks are more expressive than coroutines. An awaitable expression has a single type: the result value of the async operation. In contrast, a callback can accept multiple arguments as the result of an operation. What’s more, the callback can have overloaded function call signatures that take different sets of arguments. There is no way to automatically map such senders into awaitables. The with_awaitable_senders utility recognizes as awaitables those senders that send a single value of a single type. To await another kind of sender, a user would have to first map its value channel into a single value of a single type -- say, with the into_variant sender algorithm -- before co_await-ing that sender.

+

4.17. Cancellation of a sender can unwind a stack of coroutines

+

When looking at the sender-based retry algorithm in the previous section, we can see that the value and error cases are correctly handled. But what about cancellation? What happens to a coroutine that is suspended awaiting a sender that completes by calling execution::set_stopped?

+

When your task type’s promise inherits from with_awaitable_senders, what happens is this: the coroutine behaves as if an uncatchable exception had been thrown from the co_await expression. (It is not really an exception, but it’s helpful to think of it that way.) Provided that the promise types of the calling coroutines also inherit from with_awaitable_senders, or more generally implement a member function called unhandled_stopped, the exception unwinds the chain of coroutines as if an exception were thrown except that it bypasses catch(...) clauses.

+

In order to "catch" this uncatchable stopped exception, one of the calling coroutines in the stack would have to await a sender that maps the stopped channel into either a value or an error. That is achievable with the execution::let_stopped, execution::upon_stopped, execution::stopped_as_optional, or execution::stopped_as_error sender adaptors. For instance, we can use execution::stopped_as_optional to "catch" the stopped signal and map it into an empty optional as shown below:

+
if (auto opt = co_await execution::stopped_as_optional(some_sender)) {
+  // OK, some_sender completed successfully, and opt contains the result.
+} else {
+  // some_sender completed with a cancellation signal.
+}
+
+

As described in the section "All awaitables are senders", the sender customization points recognize awaitables and adapt them transparently to model the sender concept. When connect-ing an awaitable and a receiver, the adaptation layer awaits the awaitable within a coroutine that implements unhandled_stopped in its promise type. The effect of this is that an "uncatchable" stopped exception propagates seamlessly out of awaitables, causing execution::set_stopped to be called on the receiver.

+

Obviously, unhandled_stopped is a library extension of the coroutine promise interface. Many promise types will not implement unhandled_stopped. When an uncatchable stopped exception tries to propagate through such a coroutine, it is treated as an unhandled exception and terminate is called. The solution, as described above, is to use a sender adaptor to handle the stopped exception before awaiting it. It goes without saying that any future Standard Library coroutine types ought to implement unhandled_stopped. The author of Add lazy coroutine (coroutine task) type, which proposes a standard coroutine task type, is in agreement.

+

4.18. Composition with parallel algorithms

+

The C++ Standard Library provides a large number of algorithms that offer the potential for non-sequential execution via the use of execution policies. The set of algorithms with execution policy overloads are often referred to as "parallel algorithms", although +additional policies are available.

+

Existing policies, such as execution::par, give the implementation permission to execute the algorithm in parallel. However, the choice of execution resources used to perform the work is left to the implementation.

+

We will propose a customization point for combining schedulers with policies in order to provide control over where work will execute.

+
template<class ExecutionPolicy>
+unspecified executing_on(
+    execution::scheduler auto scheduler,
+    ExecutionPolicy && policy
+);
+
+

This function would return an object of an unspecified type which can be used in place of an execution policy as the first argument to one of the parallel algorithms. The overload selected by that object should execute its computation as requested by policy while using scheduler to create any work to be run. The expression may be ill-formed if scheduler is not able to support the given policy.

+

The existing parallel algorithms are synchronous; all of the effects performed by the computation are complete before the algorithm returns to its caller. This remains unchanged with the executing_on customization point.

+

In the future, we expect additional papers will propose asynchronous forms of the parallel algorithms which (1) return senders rather than values or void and (2) where a customization point pairing a sender with an execution policy would similarly be used to +obtain an object of unspecified type to be provided as the first argument to the algorithm.

+

4.19. User-facing sender factories

+

A sender factory is an algorithm that takes no senders as parameters and returns a sender.

+

4.19.1. execution::schedule

+
execution::sender auto schedule(
+    execution::scheduler auto scheduler
+);
+
+

Returns a sender describing the start of a task graph on the provided scheduler. See § 4.2 Schedulers represent execution resources.

+
execution::scheduler auto sch1 = get_system_thread_pool().scheduler();
+
+execution::sender auto snd1 = execution::schedule(sch1);
+// snd1 describes the creation of a new task on the system thread pool
+
+

4.19.2. execution::just

+
execution::sender auto just(
+    auto ...&& values
+);
+
+

Returns a sender with no completion schedulers, which sends the provided values. The input values are decay-copied into the returned sender. When the returned sender is connected to a receiver, the values are moved into the operation state if the sender is an rvalue; otherwise, they are copied. Then xvalues referencing the values in the operation state are passed to the receiver’s set_value.

+
execution::sender auto snd1 = execution::just(3.14);
+execution::sender auto then1 = execution::then(snd1, [] (double d) {
+  std::cout << d << "\n";
+});
+
+execution::sender auto snd2 = execution::just(3.14, 42);
+execution::sender auto then2 = execution::then(snd2, [] (double d, int i) {
+  std::cout << d << ", " << i << "\n";
+});
+
+std::vector v3{1, 2, 3, 4, 5};
+execution::sender auto snd3 = execution::just(v3);
+execution::sender auto then3 = execution::then(snd3, [] (std::vector<int>&& v3copy) {
+  for (auto&& e : v3copy) { e *= 2; }
+  return std::move(v3copy);
+}
+auto&& [v3copy] = this_thread::sync_wait(then3).value();
+// v3 contains {1, 2, 3, 4, 5}; v3copy will contain {2, 4, 6, 8, 10}.
+
+execution::sender auto snd4 = execution::just(std::vector{1, 2, 3, 4, 5});
+execution::sender auto then4 = execution::then(std::move(snd4), [] (std::vector<int>&& v4) {
+  for (auto&& e : v4) { e *= 2; }
+  return std::move(v4);
+});
+auto&& [v4] = this_thread::sync_wait(std::move(then4)).value();
+// v4 contains {2, 4, 6, 8, 10}. No vectors were copied in this example.
+
+

4.19.3. execution::just_error

+
execution::sender auto just_error(
+    auto && error
+);
+
+

Returns a sender with no completion schedulers, which completes with the specified error. If the provided error is an lvalue reference, a copy is made inside the returned sender and a non-const lvalue reference to the copy is sent to the receiver’s set_error. If the provided value is an rvalue reference, it is moved into the returned sender and an rvalue reference to it is sent to the receiver’s set_error.

+

4.19.4. execution::just_stopped

+
execution::sender auto just_stopped();
+
+

Returns a sender with no completion schedulers, which completes immediately by calling the receiver’s set_stopped.

+

4.19.5. execution::read

+
execution::sender auto read(auto tag);
+
+execution::sender auto get_scheduler() {
+  return read(execution::get_scheduler);
+}
+execution::sender auto get_delegatee_scheduler() {
+  return read(execution::get_delegatee_scheduler);
+}
+execution::sender auto get_allocator() {
+  return read(execution::get_allocator);
+}
+execution::sender auto get_stop_token() {
+  return read(execution::get_stop_token);
+}
+
+

Returns a sender that reaches into a receiver’s environment and pulls out the current value associated with the customization point denoted by Tag. It then sends the value read back to the receiver through the value channel. For instance, get_scheduler() (with no arguments) is a sender that asks the receiver for the currently suggested scheduler and passes it to the receiver’s set_value completion-signal.

+

This can be useful when scheduling nested dependent work. The following sender pulls the current schduler into the value channel and then schedules more work onto it.

+
execution::sender auto task =
+  execution::get_scheduler()
+    | execution::let_value([](auto sched) {
+        return execution::on(sched, some nested work here);
+    });
+
+this_thread::sync_wait( std::move(task) ); // wait for it to finish
+
+

This code uses the fact that sync_wait associates a scheduler with the receiver that it connects with task. get_scheduler() reads that scheduler out of the receiver, and passes it to let_value's receiver’s set_value function, which in turn passes it to the lambda. That lambda returns a new sender that uses the scheduler to schedule some nested work onto sync_wait's scheduler.

+

4.20. User-facing sender adaptors

+

A sender adaptor is an algorithm that takes one or more senders, which it may execution::connect, as parameters, and returns a sender, whose completion is related to the sender arguments it has received.

+

Sender adaptors are lazy, that is, they are never allowed to submit any work for execution prior to the returned sender being started later on, and are also guaranteed to not start any input senders passed into them. Sender consumers +such as § 4.21.1 execution::start_detached and § 4.21.2 this_thread::sync_wait start senders.

+

For more implementer-centric description of starting senders, see § 5.5 Sender adaptors are lazy.

+

4.20.1. execution::transfer

+
execution::sender auto transfer(
+    execution::sender auto input,
+    execution::scheduler auto scheduler
+);
+
+

Returns a sender describing the transition from the execution agent of the input sender to the execution agent of the target scheduler. See § 4.6 Execution resource transitions are explicit.

+
execution::scheduler auto cpu_sched = get_system_thread_pool().scheduler();
+execution::scheduler auto gpu_sched = cuda::scheduler();
+
+execution::sender auto cpu_task = execution::schedule(cpu_sched);
+// cpu_task describes the creation of a new task on the system thread pool
+
+execution::sender auto gpu_task = execution::transfer(cpu_task, gpu_sched);
+// gpu_task describes the transition of the task graph described by cpu_task to the gpu
+
+

4.20.2. execution::then

+
execution::sender auto then(
+    execution::sender auto input,
+    std::invocable<values-sent-by(input)...> function
+);
+
+

then returns a sender describing the task graph described by the input sender, with an added node of invoking the provided function with the values sent by the input sender as arguments.

+

then is guaranteed to not begin executing function until the returned sender is started.

+
execution::sender auto input = get_input();
+execution::sender auto snd = execution::then(input, [](auto... args) {
+    std::print(args...);
+});
+// snd describes the work described by pred
+// followed by printing all of the values sent by pred
+
+

This adaptor is included as it is necessary for writing any sender code that actually performs a useful function.

+

4.20.3. execution::upon_*

+
execution::sender auto upon_error(
+    execution::sender auto input,
+    std::invocable<errors-sent-by(input)...> function
+);
+
+execution::sender auto upon_stopped(
+    execution::sender auto input,
+    std::invocable auto function
+);
+
+

upon_error and upon_stopped are similar to then, but where then works with values sent by the input sender, upon_error works with errors, and upon_stopped is invoked when the "stopped" signal is sent.

+

4.20.4. execution::let_*

+
execution::sender auto let_value(
+    execution::sender auto input,
+    std::invocable<values-sent-by(input)...> function
+);
+
+execution::sender auto let_error(
+    execution::sender auto input,
+    std::invocable<errors-sent-by(input)...> function
+);
+
+execution::sender auto let_stopped(
+    execution::sender auto input,
+    std::invocable auto function
+);
+
+

let_value is very similar to then: when it is started, it invokes the provided function with the values sent by the input sender as arguments. However, where the sender returned from then sends exactly what that function ends up returning - let_value requires that the function return a sender, and the sender returned by let_value sends the values sent by the sender returned from the callback. This is similar to the notion of "future unwrapping" in future/promise-based frameworks.

+

let_value is guaranteed to not begin executing function until the returned sender is started.

+

let_error and let_stopped are similar to let_value, but where let_value works with values sent by the input sender, let_error works with errors, and let_stopped is invoked when the "stopped" signal is sent.

+

4.20.5. execution::on

+
execution::sender auto on(
+    execution::scheduler auto sched,
+    execution::sender auto snd
+);
+
+

Returns a sender which, when started, will start the provided sender on an execution agent belonging to the execution resource associated with the provided scheduler. This returned sender has no completion schedulers.

+

4.20.6. execution::into_variant

+
execution::sender auto into_variant(
+    execution::sender auto snd
+);
+
+

Returns a sender which sends a variant of tuples of all the possible sets of types sent by the input sender. Senders can send multiple sets of values depending on runtime conditions; this is a helper function that turns them into a single variant value.

+

4.20.7. execution::stopped_as_optional

+
execution::sender auto stopped_as_optional(
+    single-sender auto snd
+);
+
+

Returns a sender that maps the value channel from a T to an optional<decay_t<T>>, and maps the stopped channel to a value of an empty optional<decay_t<T>>.

+

4.20.8. execution::stopped_as_error

+
template<move_constructible Error>
+execution::sender auto stopped_as_error(
+    execution::sender auto snd,
+    Error err
+);
+
+

Returns a sender that maps the stopped channel to an error of err.

+

4.20.9. execution::bulk

+
execution::sender auto bulk(
+    execution::sender auto input,
+    std::integral auto shape,
+    invocable<decltype(size), values-sent-by(input)...> function
+);
+
+

Returns a sender describing the task of invoking the provided function with every index in the provided shape along with the values sent by the input sender. The returned sender completes once all invocations have completed, or an error has occurred. If it completes +by sending values, they are equivalent to those sent by the input sender.

+

No instance of function will begin executing until the returned sender is started. Each invocation of function runs in an execution agent whose forward progress guarantees are determined by the scheduler on which they are run. All agents created by a single use +of bulk execute with the same guarantee. The number of execution agents used by bulk is not specified. This allows a scheduler to execute some invocations of the function in parallel.

+

In this proposal, only integral types are used to specify the shape of the bulk section. We expect that future papers may wish to explore extensions of the interface to explore additional kinds of shapes, such as multi-dimensional grids, that are commonly used for +parallel computing tasks.

+

4.20.10. execution::split

+
execution::sender auto split(execution::sender auto sender);
+
+

If the provided sender is a multi-shot sender, returns that sender. Otherwise, returns a multi-shot sender which sends values equivalent to the values sent by the provided sender. See § 4.7 Senders can be either multi-shot or single-shot.

+

4.20.11. execution::when_all

+
execution::sender auto when_all(
+    execution::sender auto ...inputs
+);
+
+execution::sender auto when_all_with_variant(
+    execution::sender auto ...inputs
+);
+
+

when_all returns a sender that completes once all of the input senders have completed. It is constrained to only accept senders that can complete with a single set of values (_i.e._, it only calls one overload of set_value on its receiver). The values sent by this sender are the values sent by each of the input senders, in order of the arguments passed to when_all. It completes inline on the execution resource on which the last input sender completes, unless stop is requested before when_all is started, in which case it completes inline within the call to start.

+

when_all_with_variant does the same, but it adapts all the input senders using into_variant, and so it does not constrain the input arguments as when_all does.

+

The returned sender has no completion schedulers.

+
execution::scheduler auto sched = thread_pool.scheduler();
+
+execution::sender auto sends_1 = ...;
+execution::sender auto sends_abc = ...;
+
+execution::sender auto both = execution::when_all(sched,
+    sends_1,
+    sends_abc
+);
+
+execution::sender auto final = execution::then(both, [](auto... args){
+    std::cout << std::format("the two args: {}, {}", args...);
+});
+// when final executes, it will print "the two args: 1, abc"
+
+

4.20.12. execution::ensure_started

+
execution::sender auto ensure_started(
+    execution::sender auto sender
+);
+
+

Once ensure_started returns, it is known that the provided sender has been connected and start has been called on the resulting operation state (see § 5.2 Operation states represent work); in other words, the work described by the provided sender has been submitted +for execution on the appropriate execution resources. Returns a sender which completes when the provided sender completes and sends values equivalent to those of the provided sender.

+

If the returned sender is destroyed before execution::connect() is called, or if execution::connect() is called but the +returned operation-state is destroyed before execution::start() is called, then a stop-request is sent to the eagerly launched +operation and the operation is detached and will run to completion in the background. Its result will be discarded when it +eventually completes.

+

Note that the application will need to make sure that resources are kept alive in the case that the operation detaches. +e.g. by holding a std::shared_ptr to those resources or otherwise having some out-of-band way to signal completion of +the operation so that resource release can be sequenced after the completion.

+

4.21. User-facing sender consumers

+

A sender consumer is an algorithm that takes one or more senders, which it may execution::connect, as parameters, and does not return a sender.

+

4.21.1. execution::start_detached

+
void start_detached(
+    execution::sender auto sender
+);
+
+

Like ensure_started, but does not return a value; if the provided sender sends an error instead of a value, std::terminate is called.

+

4.21.2. this_thread::sync_wait

+
auto sync_wait(
+    execution::sender auto sender
+) requires (always-sends-same-values(sender))
+    -> std::optional<std::tuple<values-sent-by(sender)>>;
+
+

this_thread::sync_wait is a sender consumer that submits the work described by the provided sender for execution, similarly to ensure_started, except that it blocks the current std::thread or thread of main until the work is completed, and returns +an optional tuple of values that were sent by the provided sender on its completion of work. Where § 4.19.1 execution::schedule and § 4.19.2 execution::just are meant to enter the domain of senders, sync_wait is meant to exit the domain of +senders, retrieving the result of the task graph.

+

If the provided sender sends an error instead of values, sync_wait throws that error as an exception, or rethrows the original exception if the error is of type std::exception_ptr.

+

If the provided sender sends the "stopped" signal instead of values, sync_wait returns an empty optional.

+

For an explanation of the requires clause, see § 5.8 All senders are typed. That clause also explains another sender consumer, built on top of sync_wait: sync_wait_with_variant.

+

Note: This function is specified inside std::this_thread, and not inside execution. This is because sync_wait has to block the current execution agent, but determining what the current execution agent is is not reliable. Since the standard +does not specify any functions on the current execution agent other than those in std::this_thread, this is the flavor of this function that is being proposed. If C++ ever obtains fibers, for instance, we expect that a variant of this function called std::this_fiber::sync_wait would be provided. We also expect that runtimes with execution agents that use different synchronization mechanisms than std::thread's will provide their own flavors of sync_wait as well (assuming their execution agents have the means +to block in a non-deadlock manner).

+

4.22. execution::execute

+

In addition to the three categories of functions presented above, we also propose to include a convenience function for fire-and-forget eager one-way submission of an invocable to a scheduler, to fulfil the role of one-way executors from P0443.

+
void execution::execute(
+    execution::schedule auto sched,
+    std::invocable auto fn
+);
+
+

Submits the provided function for execution on the provided scheduler, as-if by:

+
auto snd = execution::schedule(sched);
+auto work = execution::then(snd, fn);
+execution::start_detached(work);
+
+

5. Design - implementer side

+

5.1. Receivers serve as glue between senders

+

A receiver is a callback that supports more than one channel. In fact, it supports three of them:

+
    +
  • +

    set_value, which is the moral equivalent of an operator() or a function +call, which signals successful completion of the operation its execution +depends on;

    +
  • +

    set_error, which signals that an error has happened during scheduling of the +current work, executing the current work, or at some earlier point in the +sender chain; and

    +
  • +

    set_stopped, which signals that the operation completed without succeeding +(set_value) and without failing (set_error). This result is often used +to indicate that the operation stopped early, typically because it was asked +to do so because the result is no longer needed.

    +
+

Once an async operation has been started exactly one of these functions must be invoked +on a receiver before it is destroyed.

+

While the receiver interface may look novel, it is in fact very similar to the +interface of std::promise, which provides the first two signals as set_value and set_exception, and it’s possible to emulate the third channel with +lifetime management of the promise.

+

Receivers are not a part of the end-user-facing API of this proposal; they are necessary to allow unrelated senders communicate with each other, but the only users who will interact with receivers directly are authors of senders.

+

Receivers are what is passed as the second argument to § 5.3 execution::connect.

+

5.2. Operation states represent work

+

An operation state is an object that represents work. Unlike senders, it is not a chaining mechanism; instead, it is a concrete object that packages the work described by a full sender chain, ready to be executed. An operation state is neither movable nor +copyable, and its interface consists of a single algorithm: start, which serves as the submission point of the work represented by a given operation state.

+

Operation states are not a part of the user-facing API of this proposal; they are necessary for implementing sender consumers like execution::ensure_started and this_thread::sync_wait, and the knowledge of them is necessary to implement senders, so the only users who will +interact with operation states directly are authors of senders and authors of sender algorithms.

+

The return value of § 5.3 execution::connect must satisfy the operation state concept.

+

5.3. execution::connect

+

execution::connect is a customization point which connects senders with receivers, resulting in an operation state that will ensure that if start is called that one of the completion operations will be called on the receiver passed to connect.

+
execution::sender auto snd = some input sender;
+execution::receiver auto rcv = some receiver;
+execution::operation_state auto state = execution::connect(snd, rcv);
+
+execution::start(state);
+// at this point, it is guaranteed that the work represented by state has been submitted
+// to an execution resource, and that execution resource will eventually call one of the
+// completion operations on rcv
+
+// operation states are not movable, and therefore this operation state object must be
+// kept alive until the operation finishes
+
+

5.4. Sender algorithms are customizable

+

Senders being able to advertise what their completion schedulers are fulfills one of the promises of senders: that of being able to customize an implementation of a sender algorithm based on what scheduler any work it depends on will complete on.

+

The simple way to provide customizations for functions like then, that is for sender adaptors and sender consumers, is to follow the customization scheme that has been adopted for C++20 ranges library; to do that, we would define +the expression execution::then(sender, invocable) to be equivalent to:

+
    +
  1. +

    sender.then(invocable), if that expression is well-formed; otherwise

    +
  2. +

    then(sender, invocable), performed in a context where this call always performs ADL, if that expression is well-formed; otherwise

    +
  3. +

    a default implementation of then, which returns a sender adaptor, and then define the exact semantics of said adaptor.

    +
+

However, this definition is problematic. Imagine another sender adaptor, bulk, which is a structured abstraction for a loop over an index space. Its default implementation is just a for loop. However, for accelerator runtimes like CUDA, we would like sender algorithms +like bulk to have specialized behavior, which invokes a kernel of more than one thread (with its size defined by the call to bulk); therefore, we would like to customize bulk for CUDA senders to achieve this. However, there’s no reason for CUDA kernels to +necessarily customize the then sender adaptor, as the generic implementation is perfectly sufficient. This creates a problem, though; consider the following snippet:

+
execution::scheduler auto cuda_sch = cuda_scheduler{};
+
+execution::sender auto initial = execution::schedule(cuda_sch);
+// the type of initial is a type defined by the cuda_scheduler
+// let’s call it cuda::schedule_sender<>
+
+execution::sender auto next = execution::then(cuda_sch, []{ return 1; });
+// the type of next is a standard-library unspecified sender adaptor
+// that wraps the cuda sender
+// let’s call it execution::then_sender_adaptor<cuda::schedule_sender<>>
+
+execution::sender auto kernel_sender = execution::bulk(next, shape, [](int i){ ... });
+
+

How can we specialize the bulk sender adaptor for our wrapped schedule_sender? Well, here’s one possible approach, taking advantage of ADL (and the fact that the definition of "associated namespace" also recursively enumerates the associated namespaces of all template +parameters of a type):

+
namespace cuda::for_adl_purposes {
+template<typename... SentValues>
+class schedule_sender {
+    execution::operation_state auto connect(execution::receiver auto rcv);
+    execution::scheduler auto get_completion_scheduler() const;
+};
+
+execution::sender auto bulk(
+    execution::sender auto && input,
+    execution::shape auto && shape,
+    invocable%lt;sender-values(input)> auto && fn)
+{
+    // return a cuda sender representing a bulk kernel launch
+}
+} // namespace cuda::for_adl_purposes
+
+

However, if the input sender is not just a then_sender_adaptor like in the example above, but another sender that overrides bulk by itself, as a member function, because its author believes they know an optimization for bulk - the specialization above will no +longer be selected, because a member function of the first argument is a better match than the ADL-found overload.

+

This means that well-meant specialization of sender algorithms that are entirely scheduler-agnostic can have negative consequences. +The scheduler-specific specialization - which is essential for good performance on platforms providing specialized ways to launch certain sender algorithms - would not be selected in such cases. +But it’s really the scheduler that should control the behavior of sender algorithms when a non-default implementation exists, not the sender. Senders merely describe work; schedulers, however, are the handle to the +runtime that will eventually execute said work, and should thus have the final say in how the work is going to be executed.

+

Therefore, we are proposing the following customization scheme (also modified to take § 5.9 Ranges-style CPOs vs tag_invoke into account): the expression execution::<sender-algorithm>(sender, args...), for any given sender algorithm that accepts a sender as its first argument, should be +equivalent to:

+
    +
  1. +

    tag_invoke(<sender-algorithm>, get_completion_scheduler<Tag>(get_env(sender)), sender, args...), if that expression is well-formed; otherwise

    +
  2. +

    tag_invoke(<sender-algorithm>, sender, args...), if that expression is well-formed; otherwise

    +
  3. +

    a default implementation, if there exists a default implementation of the given sender algorithm.

    +
+

where Tag is one of set_value, set_error, or set_stopped. For most sender algorithms, the completion scheduler for set_value would be used, but for some (like upon_error or let_stopped), one of the others would be used.

+

For sender algorithms which accept concepts other than sender as their first argument, we propose that the customization scheme remains as it has been in A Unified Executors Proposal for C++ so far, except it should also use tag_invoke.

+

5.5. Sender adaptors are lazy

+

Contrary to early revisions of this paper, we propose to make all sender adaptors perform strictly lazy submission, unless specified otherwise (the one notable exception in this paper is § 4.20.12 execution::ensure_started, whose sole purpose is to start an +input sender).

+

Strictly lazy submission means that there is a guarantee that no work is submitted to an execution resource before a receiver is connected to a sender, and execution::start is called on the resulting operation state.

+

5.6. Lazy senders provide optimization opportunities

+

Because lazy senders fundamentally describe work, instead of describing or representing the submission of said work to an execution resource, and thanks to the flexibility of the customization of most sender algorithms, they provide an opportunity for fusing +multiple algorithms in a sender chain together, into a single function that can later be submitted for execution by an execution resource. There are two ways this can happen.

+

The first (and most common) way for such optimizations to happen is thanks to the structure of the implementation: because all the work is done within callbacks invoked on the completion of an earlier sender, recursively up to the original source of computation, +the compiler is able to see a chain of work described using senders as a tree of tail calls, allowing for inlining and removal of most of the sender machinery. In fact, when work is not submitted to execution resources outside of the current thread of execution, +compilers are capable of removing the senders abstraction entirely, while still allowing for composition of functions across different parts of a program.

+

The second way for this to occur is when a sender algorithm is specialized for a specific set of arguments. For instance, we expect that, for senders which are known to have been started already, § 4.20.12 execution::ensure_started will be an identity transformation, +because the sender algorithm will be specialized for such senders. Similarly, an implementation could recognize two subsequent § 4.20.9 execution::bulks of compatible shapes, and merge them together into a single submission of a GPU kernel.

+

5.7. Execution resource transitions are two-step

+

Because execution::transfer takes a sender as its first argument, it is not actually directly customizable by the target scheduler. This is by design: the target scheduler may not know how to transition from a scheduler such as a CUDA scheduler; +transitioning away from a GPU in an efficient manner requires making runtime calls that are specific to the GPU in question, and the same is usually true for other kinds of accelerators too (or for scheduler running on remote systems). To avoid this problem, +specialized schedulers like the ones mentioned here can still hook into the transition mechanism, and inject a sender which will perform a transition to the regular CPU execution resource, so that any sender can be attached to it.

+

This, however, is a problem: because customization of sender algorithms must be controlled by the scheduler they will run on (see § 5.4 Sender algorithms are customizable), the type of the sender returned from transfer must be controllable by the target scheduler. Besides, the target +scheduler may itself represent a specialized execution resource, which requires additional work to be performed to transition to it. GPUs and remote node schedulers are once again good examples of such schedulers: executing code on their execution resources +requires making runtime API calls for work submission, and quite possibly for the data movement of the values being sent by the input sender passed into transfer.

+

To allow for such customization from both ends, we propose the inclusion of a secondary transitioning sender adaptor, called schedule_from. This adaptor is a form of schedule, but takes an additional, second argument: the input sender. This adaptor is not +meant to be invoked manually by the end users; they are always supposed to invoke transfer, to ensure that both schedulers have a say in how the transitions are made. Any scheduler that specializes transfer(snd, sch) shall ensure that the +return value of their customization is equivalent to schedule_from(sch, snd2), where snd2 is a successor of snd that sends values equivalent to those sent by snd.

+

The default implementation of transfer(snd, sched) is schedule_from(sched, snd).

+

5.8. All senders are typed

+

All senders must advertise the types they will send when they complete. +This is necessary for a number of features, and writing code in a way that’s +agnostic of whether an input sender is typed or not in common sender adaptors +such as execution::then is hard.

+

The mechanism for this advertisement is similar to the one in A Unified Executors Proposal for C++; the +way to query the types is through completion_signatures_of_t<S, [Env]>::value_types<tuple_like, variant_like>.

+

completion_signatures_of_t::value_types is a template that takes two +arguments: one is a tuple-like template, the other is a variant-like template. +The tuple-like argument is required to represent senders sending more than one +value (such as when_all). The variant-like argument is required to represent +senders that choose which specific values to send at runtime.

+

There’s a choice made in the specification of § 4.21.2 this_thread::sync_wait: it returns a tuple of values sent by the +sender passed to it, wrapped in std::optional to handle the set_stopped signal. However, this assumes that those values can be represented as a tuple, +like here:

+
execution::sender auto sends_1 = ...;
+execution::sender auto sends_2 = ...;
+execution::sender auto sends_3 = ...;
+
+auto [a, b, c] = this_thread::sync_wait(
+    execution::when_all(
+        sends_1,
+        sends_2,
+        sends_3)
+    | execution::transfer(
+        execution::get_completion_scheduler<execution::set_value_t>(get_env(sends_1))),
+    ).value();
+// a == 1
+// b == 2
+// c == 3
+
+

This works well for senders that always send the same set of arguments. If we ignore the possibility of having a sender that sends different sets of arguments into a receiver, we can specify the "canonical" (i.e. required to be followed by all senders) form of value_types of a sender which sends Types... to be as follows:

+
template<template<typename ...> typename TupleLike>
+using value_types = TupleLike;
+
+

If senders could only ever send one specific set of values, this would probably need to be the required form of value_types for all senders; defining it otherwise would cause very weird results and should be considered a bug.

+

This matter is somewhat complicated by the fact that (1) set_value for receivers can be overloaded and accept different sets of arguments, and (2) senders are allowed to send multiple different sets of values, depending on runtime conditions, the data they +consumed, and so on. To accomodate this, A Unified Executors Proposal for C++ also includes a second template parameter to value_types, one that represents a variant-like type. If we permit such senders, we would almost certainly need to require that the canonical form of value_types for all senders (to ensure consistency in how they are handled, and to avoid accidentally interpreting a user-provided variant as a sender-provided one) sending the different sets of arguments Types1..., Types2..., ..., TypesN... to be as follows:

+
template<
+    template<typename ...> typename TupleLike,
+    template<typename ...> typename VariantLike
+>
+using value_types = VariantLike<
+    TupleLike<Types1...>,
+    TupleLike<Types2...>,
+    ...,
+    TupleLike<Types3...>
+>;
+
+

This, however, introduces a couple of complications:

+
    +
  1. +

    A just(1) sender would also need to follow this structure, so the correct type for storing the value sent by it would be std::variant<std::tuple<int>> or some such. This introduces a lot of compile time overhead for the simplest senders, and this overhead +effectively exists in all places in the code where value_types is queried, regardless of the tuple-like and variant-like templates passed to it. Such overhead does exist if only the tuple-like parameter exists, but is made much worse by adding this second +wrapping layer.

    +
  2. +

    As a consequence of (1): because sync_wait needs to store the above type, it can no longer return just a std::tuple<int> for just(1); it has to return std::variant<std::tuple<int>>. C++ currently does not have an easy way to destructure this; it may get +less awkward with pattern matching, but even then it seems extremely heavyweight to involve variants in this API, and for the purpose of generic code, the kind of the return type of sync_wait must be the same across all sender types.

    +
+

One possible solution to (2) above is to place a requirement on sync_wait that it can only accept senders which send only a single set of values, therefore removing the need for std::variant to appear in its API; because of this, we propose to expose both sync_wait, which is a simple, user-friendly version of the sender consumer, but requires that value_types have only one possible variant, and sync_wait_with_variant, which accepts any sender, but returns an optional whose value type is the variant of all the +possible tuples sent by the input sender:

+
auto sync_wait_with_variant(
+    execution::sender auto sender
+) -> std::optional<std::variant<
+        std::tuple<values0-sent-by(sender)>,
+        std::tuple<values1-sent-by(sender)>,
+        ...,
+        std::tuple<valuesn-sent-by(sender)>
+    >>;
+
+auto sync_wait(
+    execution::sender auto sender
+) requires (always-sends-same-values(sender))
+    -> std::optional<std::tuple<values-sent-by(sender)>>;
+
+

5.9. Ranges-style CPOs vs tag_invoke

+

The contemporary technique for customization in the Standard Library is customization point objects. A customization point object, will it look for member functions and then for nonmember functions with the same name as the customization point, and calls those if +they match. This is the technique used by the C++20 ranges library, and previous executors proposals (A Unified Executors Proposal for C++ and Towards C++23 executors: A proposal for an initial set of algorithms) intended to use it as well. However, it has several unfortunate consequences:

+
    +
  1. +

    It does not allow for easy propagation of customization points unknown to the adaptor to a wrapped object, which makes writing universal adapter types much harder - and this proposal uses quite a lot of those.

    +
  2. +

    It effectively reserves names globally. Because neither member names nor ADL-found functions can be qualified with a namespace, every customization point object that uses the ranges scheme reserves the name for all types in all namespaces. This is unfortunate +due to the sheer number of customization points already in the paper, but also ones that we are envisioning in the future. It’s also a big problem for one of the operations being proposed already: sync_wait. We imagine that if, in the future, C++ was to +gain fibers support, we would want to also have std::this_fiber::sync_wait, in addition to std::this_thread::sync_wait. However, because we would want the names to be the same in both cases, we would need to make the names of the customizations not match the +names of the customization points. This is undesirable.

    +
+

This paper proposes to instead use the mechanism described in tag_invoke: A general pattern for supporting customisable functions: tag_invoke; the wording for tag_invoke has been incorporated into the proposed specification in this paper.

+

In short, instead of using globally reserved names, tag_invoke uses the type of the customization point object itself as the mechanism to find customizations. It globally reserves only a single name - tag_invoke - which itself is used the same way that +ranges-style customization points are used. All other customization points are defined in terms of tag_invoke. For example, the customization for std::this_thread::sync_wait(s) will call tag_invoke(std::this_thread::sync_wait, s), instead of attempting +to invoke s.sync_wait(), and then sync_wait(s) if the member call is not valid.

+

Using tag_invoke has the following benefits:

+
    +
  1. +

    It reserves only a single global name, instead of reserving a global name for every customization point object we define.

    +
  2. +

    It is possible to propagate customizations to a subobject, because the information of which customization point is being resolved is in the type of an argument, and not in the name of the function:

    +
    // forward most customizations to a subobject
    +template<typename Tag, typename ...Args>
    +friend auto tag_invoke(Tag && tag, wrapper & self, Args &&... args) {
    +    return std::forward<Tag>(tag)(self.subobject, std::forward<Args>(args)...);
    +}
    +
    +// but override one of them with a specific value
    +friend auto tag_invoke(specific_customization_point_t, wrapper & self) {
    +    return self.some_value;
    +}
    +
    +
  3. +

    It is possible to pass those as template arguments to types, because the information of which customization point is being resolved is in the type. Similarly to how A Unified Executors Proposal for C++ defines a polymorphic executor wrapper which accepts a list of properties it +supports, we can imagine scheduler and sender wrappers that accept a list of queries and operations they support. That list can contain the types of the customization point objects, and the polymorphic wrappers can then specialize those customization points on +themselves using tag_invoke, dispatching to manually constructed vtables containing pointers to specialized implementations for the wrapped objects. For an example of such a polymorphic wrapper, see unifex::any_unique (example).

    +
+

6. Specification

+

Much of this wording follows the wording of A Unified Executors Proposal for C++.

+

§ 8 Library introduction [library] is meant to be a diff relative to the wording of the [library] clause of Working Draft, Standard for Programming Language C++.

+

§ 9 General utilities library [utilities] is meant to be a diff relative to the wording of the [utilities] clause of Working Draft, Standard for Programming Language C++. This diff applies changes from tag_invoke: A general pattern for supporting customisable functions.

+

§ 10 Thread support library [thread] is meant to be a diff relative to the wording of the [thread] clause of Working Draft, Standard for Programming Language C++. This diff applies changes from Composable cancellation for sender-based async operations.

+

§ 11 Execution control library [exec] is meant to be added as a new library clause to the working draft of C++.

+

7. Exception handling [except]

+

7.1. Special functions [except.special]

+

7.1.1. General [except.special.general]

+
7.1.1.1. The std::terminate function [except.terminate]
+
At the end of the bulleted list in the Note in paragraph 1, add a new bullet as follows:
+ +
+
    +
  • +

    when a callback invocation exits via an exception when requesting stop on a std::stop_source or a std::in_place_stop_source ([stopsource.mem], [stopsource.inplace.mem]), or in +the constructor of std::stop_callback or std::in_place_stop_callback ([stopcallback.cons], [stopcallback.inplace.cons]) when a callback invocation exits +via an exception.

    +
+
+
+

8. Library introduction [library]

+
Add the header <execution> to Table 23: C++ library +headers [tab:headers.cpp]
+
At the end of [expos.only.entity], add the following:
+ +
+
    +
  1. +

    An object dst is said to be decay-copied from a +subexpression src if the type of dst is decay_t<decltype((src))>, +and dst is copy-initialized from src.

    +
+
+
+
In subclause [conforming], after [lib.types.movedfrom], +add the following new subclause with suggested stable name [lib.tmpl-heads].
+ +
+ 16.4.6.17 Class template-heads +
    +
  1. +

    If a class template’s template-head is marked with "arguments are not +associated entities"", any template arguments do not contribute to the +associated entities ([basic.lookup.argdep]) of a function call where a +specialization of the class template is an associated entity. In such a case, +the class template can be implemented as an alias template referring to a +templated class, or as a class template where the template arguments +themselves are templated classes.

    +
  2. +

    [Example:

    +
    template<class T> // arguments are not associated entities
    +struct S {};
    +
    +namespace N {
    +  int f(auto);
    +  struct A {};
    +}
    +
    +int x = f(S<N::A>{});  // error: N::f not a candidate
    +
    +

    The template S specified above can be implemented as

    +
    template<class T>
    +struct s-impl {
    +  struct type { };
    +};
    +
    +template<class T>
    +using S = s-impl<T>::type;
    +
    +

    or as

    +
    template<class T>
    +struct hidden {
    +  using type = struct _ {
    +    using type = T;
    +  };
    +};
    +
    +template<class HiddenT>
    +struct s-impl {
    +  using T = HiddenT::type;
    +};
    +
    +template<class T>
    +using S = s-impl<typename hidden<T>::type>;
    +
    +

    -- end example]

    +
+
+
+

9. General utilities library [utilities]

+

9.1. Function objects [function.objects]

+

9.1.1. Header <functional> synopsis [functional.syn]

+

At the end of this subclause, insert the following declarations into the synopsis within namespace std:

+ +
+
// expositon only:
+template<class Fn, class... Args>
+  concept callable =
+    requires (Fn&& fn, Args&&... args) {
+      std::forward<Fn>(fn)(std::forward<Args>(args)...);
+    };
+template<class Fn, class... Args>
+  concept nothrow-callable =
+    callable<Fn, Args...> &&
+    requires (Fn&& fn, Args&&... args) {
+      { std::forward<Fn>(fn)(std::forward<Args>(args)...) } noexcept;
+    };
+template<class Fn, class... Args>
+  using call-result-t = decltype(declval<Fn>()(declval<Args>()...));
+
+// [func.tag_invoke], tag_invoke
+namespace tag-invoke { // exposition only
+  void tag_invoke();
+
+  template<class Tag, class... Args>
+    concept tag_invocable =
+      requires (Tag&& tag, Args&&... args) {
+        tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
+      };
+
+  template<class Tag, class... Args>
+    concept nothrow_tag_invocable =
+      tag_invocable<Tag, Args...> &&
+      requires (Tag&& tag, Args&&... args) {
+        { tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...) } noexcept;
+      };
+
+  template<class Tag, class... Args>
+    using tag_invoke_result_t =
+      decltype(tag_invoke(declval<Tag>(), declval<Args>()...));
+
+  template<class Tag, class... Args>
+    struct tag_invoke_result<Tag, Args...> {
+      using type =
+        tag_invoke_result_t<Tag, Args...>; // present if and only if tag_invocable<Tag, Args...> is true
+    };
+
+  struct tag; // exposition only
+}
+inline constexpr tag-invoke::tag tag_invoke {};
+using tag-invoke::tag_invocable;
+using tag-invoke::nothrow_tag_invocable;
+using tag-invoke::tag_invoke_result_t;
+using tag-invoke::tag_invoke_result;
+
+template<auto& Tag>
+  using tag_t = decltype(auto(Tag));
+
+
+
+

9.1.2. tag_invoke [func.tag_invoke]

+

Insert this subclause as a new subclause, between Searchers [func.search] and Class template hash [unord.hash].

+ +
+
    +
  1. +

    Given a subexpression E, let REIFY(E) be expression-equivalent to +a glvalue with the same type and value as E as if by identity()(E).

    +
  2. +

    The name std::tag_invoke denotes a customization point object [customization.point.object]. +Given subexpressions T and A..., the expression std::tag_invoke(T, A...) is +expression-equivalent [defns.expression-equivalent] to tag_invoke(REIFY(T), REIFY(A)...) with overload resolution performed in a context in which unqualified lookup for tag_invoke finds only the declaration

    +
    void tag_invoke();
    +
    +
  3. +

    [Note: Diagnosable ill-formed cases above result in substitution failure when std::tag_invoke(T, A...) appears in the immediate context of a template instantiation. —end note]

    +
+
+
+

10. Thread support library [thread]

+

10.1. Stop tokens [thread.stoptoken]

+

10.1.1. Header <stop_token> synopsis [thread.stoptoken.syn]

+

At the beginning of this subclause, insert the following declarations into the synopsis within namespace std:

+ +
+
template<template<class> class>
+  struct check-type-alias-exists; // exposition-only
+
+template<class T>
+  concept stoppable_token = see below;
+
+template<class T, class CB, class Initializer = CB>
+  concept stoppable_token_for = see below;
+
+template<class T>
+  concept unstoppable_token = see below;
+
+
+
+

At the end of this subclause, insert the following declarations into the synopsis of within namespace std:

+ +
+
// [stoptoken.never], class never_stop_token
+class never_stop_token;
+
+// [stoptoken.inplace], class in_place_stop_token
+class in_place_stop_token;
+
+// [stopsource.inplace], class in_place_stop_source
+class in_place_stop_source;
+
+// [stopcallback.inplace], class template in_place_stop_callback
+template<class CB>
+  class in_place_stop_callback;
+
+template<class T, class CB>
+  using stop_callback_for_t = T::template callback_type<CB>;
+
+
+
+

10.1.2. Stop token concepts [thread.stoptoken.concepts]

+

Insert this subclause as a new subclause between Header <stop_token> synopsis [thread.stoptoken.syn] and Class stop_token [stoptoken].

+ +
+
    +
  1. +

    The stoppable_token concept checks for the basic interface of a stop token +that is copyable and allows polling to see if stop has been requested and +also whether a stop request is possible. For a stop token type T and a type CB that is callable with no arguments, the type T::callback_type<CB> is +valid and denotes the stop callback type to use to register a callback +to be executed if a stop request is ever made on a stoppable_token of type T. The stoppable_token_for concept checks for a stop token type compatible +with a given callback type. The unstoppable_token concept checks for a stop +token type that does not allow stopping.

    +
+
template<class T>
+  concept stoppable_token =
+    copyable<T> &&
+    equality_comparable<T> &&
+    requires (const T t) {
+      { T(t) } noexcept; // see implicit expression variations ([concepts.equality])
+      { t.stop_requested() } noexcept -> same_as<bool>;
+      { t.stop_possible() } noexcept -> same_as<bool>;
+      typename check-type-alias-exists<T::template callback_type>;
+    };
+
+template<class T, class CB, class Initializer = CB>
+  concept stoppable_token_for =
+    stoppable_token<T> &&
+    invocable<CB> &&
+    constructible_from<CB, Initializer> &&
+    requires { typename stop_callback_for_t<T, CB>; } &&
+    constructible_from<stop_callback_for_t<T, CB>, const T&, Initializer>;
+
+template<class T>
+  concept unstoppable_token =
+    stoppable_token<T> &&
+    requires {
+      { bool_constant<T::stop_possible()>{} } -> same_as<false_type>;
+    };
+
+
+ LWG directed me to replace T::stop_possible() with t.stop_possible() because +of the recent constexpr changes in P2280R2. However, even with those changes, a nested +requirement like requires (!t.stop_possible()), where t is an argument in the requirement-parameter-list, is ill-formed according to [expr.prim.req.nested/p2]: +
+

A local parameter shall only appear as an unevaluated operand within the constraint-expression.

+
+

This is the subject of core issue 2517.

+
+
    +
  1. +

    Let t and u be distinct, valid objects of type T. The type T models stoppable_token only if:

    +
      +
    1. +

      If t.stop_possible() evaluates to false then, if t and u reference the same logical shared stop state, u.stop_possible() shall also subsequently evaluate to false and u.stop_requested() shall also subsequently evaluate to false.

      +
    2. +

      If t.stop_requested() evaluates to true then, if t and u reference the same logical shared stop state, u.stop_requested() shall also subsequently evaluate to true and u.stop_possible() shall also subsequently evaluate to true.

      +
    +
  2. +

    Let t and u be distinct, valid objects of type T and let init be an +object of type Initializer. Then for some type CB, the type T models stoppable_token_for<CB, Initializer> only if:

    +
      +
    1. +

      The type T::callback_type<CB> models:

      +
      constructible_from<T, Initializer> &&
      +constructible_from<T&, Initializer> &&
      +constructible_from<const T, Initializer>
      +
      +
    2. +

      Direct non-list initializing an object cb of type T::callback_type<CB> from t, init shall, if t.stop_possible() is true, construct an +instance, callback, of type CB, direct-initialized with init, +and register callback with t's shared stop state such that callback will be invoked with an empty argument list if a stop request is made +on the shared stop state.

      +
        +
      1. +

        If t.stop_requested() evaluates to true at the time callback is +registered then callback can be invoked on the thread executing cb's constructor.

        +
      2. +

        If callback is invoked then, if t and u reference the same shared stop +state, an evaluation of u.stop_requested() will be true if the beginning of the invocation of callback strongly-happens-before the evaluation of u.stop_requested().

        +
      3. +

        [Note: If t.stop_possible() evaluates to false then the construction of cb is not required to construct and initialize callback. --end note]

        +
      +
    3. +

      Construction of a T::callback_type<CB> instance shall only throw exceptions thrown by the initialization of the CB instance from the value of type Initializer.

      +
    4. +

      Destruction of the T::callback_type<CB> object, cb, removes callback from the shared stop state such that callback will not be invoked after the destructor returns.

      +
        +
      1. +

        If callback is currently being invoked on another thread then the destructor of cb will block until the invocation of callback returns such that the return from the invocation of callback strongly-happens-before the destruction of callback.

        +
      2. +

        Destruction of a callback cb shall not block on the completion of the invocation of some other callback registered with the same shared stop state.

        +
      +
    +
+
+
+

10.1.3. Class stop_token [stoptoken]

+
10.1.3.1. General [stoptoken.general]
+

Modify the synopsis of class stop_token in subclause General [stoptoken.general] as follows:

+
namespace std {
+  class stop_token {
+  public:
+    template<class T>
+      using callback_type = stop_callback<T>;
+
+    // [stoptoken.cons], constructors, copy, and assignment
+    stop_token() noexcept;
+
+    // ...
+
+

10.1.4. Class never_stop_token [stoptoken.never]

+

Insert a new subclause, Class never_stop_token [stoptoken.never], after subclause Class template stop_callback [stopcallback], as a new subclause of Stop tokens [thread.stoptoken].

+
10.1.4.1. General [stoptoken.never.general]
+
    +
  1. +

    The class never_stop_token provides an implementation of the unstoppable_token concept. It provides a stop token interface, but also provides static information that a stop is never possible nor requested.

    +
+
namespace std
+{
+  class never_stop_token {
+    // exposition only
+    struct callback {
+      explicit callback(never_stop_token, auto&&) noexcept {}
+    };
+  public:
+    template<class>
+      using callback_type = callback;
+
+    [[nodiscard]] static constexpr bool stop_requested() noexcept { return false; }
+    [[nodiscard]] static constexpr bool stop_possible() noexcept { return false; }
+
+    [[nodiscard]] friend bool operator==(const never_stop_token&, const never_stop_token&) noexcept = default;
+  };
+}
+
+

10.1.5. Class in_place_stop_token [stoptoken.inplace]

+

Insert a new subclause, Class in_place_stop_token [stoptoken.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].

+
10.1.5.1. General [stoptoken.inplace.general]
+
    +
  1. +

    The class in_place_stop_token provides an interface for querying whether a stop request has been made (stop_requested) or can ever be made (stop_possible) using an associated in_place_stop_source object ([stopsource.inplace]). +An in_place_stop_token can also be passed to an in_place_stop_callback ([stopcallback.inplace]) constructor to register a callback to be called when a stop request has been made from an associated in_place_stop_source.

    +
+
namespace std {
+  class in_place_stop_token {
+  public:
+    template<class CB>
+      using callback_type = in_place_stop_callback<CB>;
+
+    // [stoptoken.inplace.cons], constructors, copy, and assignment
+    in_place_stop_token() noexcept;
+    ~in_place_stop_token();
+    void swap(in_place_stop_token&) noexcept;
+
+    // [stoptoken.inplace.mem], stop handling
+    [[nodiscard]] bool stop_requested() const noexcept;
+    [[nodiscard]] bool stop_possible() const noexcept;
+
+    [[nodiscard]] friend bool operator==(const in_place_stop_token&, const in_place_stop_token&) noexcept = default;
+    friend void swap(in_place_stop_token& lhs, in_place_stop_token& rhs) noexcept;
+
+  private:
+    const in_place_stop_source* source_; // exposition only
+  };
+}
+
+
10.1.5.2. Constructors, copy, and assignment [stoptoken.inplace.cons]
+
in_place_stop_token() noexcept;
+
+
    +
  1. +

    Effects: initializes source_ with nullptr.

    +
+
void swap(stop_token& rhs) noexcept;
+
+
    +
  1. +

    Effects: Exchanges the values of source_ and rhs.source_.

    +
+
10.1.5.3. Members [stoptoken.inplace.mem]
+
[[nodiscard]] bool stop_requested() const noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: return source_ != nullptr && source_->stop_requested();

    +
  2. +

    [Note: The behavior of stop_requested() is undefined unless the call +strongly happens before the start of the destructor of the associated in_place_stop_source, if any ([basic.life]). --end note]

    +
+
[[nodiscard]] bool stop_possible() const noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: return source_ != nullptr;

    +
  2. +

    [Note: The behavior of stop_possible() is implementation-defined unless +the call strongly happens before the end of the storage duration of the +associated in_place_stop_source object, if any ([basic.stc.general]). --end note]

    +
+
10.1.5.4. Non-member functions [stoptoken.inplace.nonmembers]
+
friend void swap(in_place_stop_token& x, in_place_stop_token& y) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: x.swap(y).

    +
+

10.1.6. Class in_place_stop_source [stopsource.inplace]

+

Insert a new subclause, Class in_place_stop_source [stopsource.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].

+
10.1.6.1. General [stopsource.inplace.general]
+
    +
  1. +

    The class in_place_stop_source implements the semantics of making a stop request, without the need for a dynamic allocation of a shared state. +A stop request made on a in_place_stop_source object is visible to all associated in_place_stop_token ([stoptoken.inplace]) objects. +Once a stop request has been made it cannot be withdrawn (a subsequent stop request has no effect). +All uses of in_place_stop_token objects associated with a given in_place_stop_source object must happen before the start of the destructor of that in_place_stop_source object.

    +
+
namespace std {
+  class in_place_stop_source {
+  public:
+    // [stopsource.inplace.cons], constructors, copy, and assignment
+    in_place_stop_source() noexcept;
+
+    in_place_stop_source(in_place_stop_source&&) noexcept = delete;
+    ~in_place_stop_source();
+
+    //[stopsource.inplace.mem], stop handling
+    [[nodiscard]] in_place_stop_token get_token() const noexcept;
+    [[nodiscard]] static constexpr bool stop_possible() noexcept { return true; }
+    [[nodiscard]] bool stop_requested() const noexcept;
+    bool request_stop() noexcept;
+  };
+}
+
+
    +
  1. +

    An instance of in_place_stop_source maintains a list of registered callback invocations. +The registration of a callback invocation either succeeds or fails. When an invocation +of a callback is registered, the following happens atomically:

    +
      +
    • +

      The stop state is checked. If stop has not been requested, the callback invocation is +added to the list of registered callback invocations, and registration has succeeded.

      +
    • +

      Otherwise, registration has failed.

      +
    +

    When an invocation of a callback is unregistered, the invocation is atomically removed +from the list of registered callback invocations. The removal is not blocked by the concurrent +execution of another callback invocation in the list. If the callback invocation +being unregistered is currently executing, then:

    +
      +
    • +

      If the execution of the callback invocation is happening concurrently on another thread, +the completion of the execution strongly happens before ([intro.races]) the end of the +callback’s lifetime.

      +
    • +

      Otherwise, the execution is happening on the current thread. Removal of the +callback invocation does not block waiting for the execution to complete.

      +
    +
+
10.1.6.2. Constructors, copy, and assignment [stopsource.inplace.cons]
+
in_place_stop_source() noexcept;
+
+
    +
  1. +

    Effects: Initializes a new stop state inside *this.

    +
  2. +

    Postconditions: stop_requested() is false.

    +
+
10.1.6.3. Members [stopsource.inplace.mem]
+
[[nodiscard]] in_place_stop_token get_token() const noexcept;
+
+
    +
  1. +

    Returns: A new associated in_place_stop_token object.

    +
+
[[nodiscard]] bool stop_requested() const noexcept;
+
+
    +
  1. +

    Returns: true if the stop state inside *this has received a stop request; otherwise, false.

    +
+
bool request_stop() noexcept;
+
+
    +
  1. +

    Effects: Atomically determines whether the stop state inside *this has received a stop request, and if not, makes a stop request. +The determination and making of the stop request are an atomic read-modify-write operation ([intro.races]). +If the request was made, the registered invocations are executed and the evaluations of the invocations are indeterminately sequenced. +If an invocation of a callback exits via an exception then terminate is invoked ([except.terminate]).

    +
  2. +

    Postconditions: stop_requested() is true.

    +
  3. +

    Returns: true if this call made a stop request; otherwise false.

    +
+

10.1.7. Class template in_place_stop_callback [stopcallback.inplace]

+

Insert a new subclause, Class template in_place_stop_callback [stopcallback.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].

+
10.1.7.1. General [stopcallback.inplace.general]
+
    +
  1. +
    namespace std {
    +  template<class Callback>
    +  class in_place_stop_callback {
    +  public:
    +    using callback_type = Callback;
    +
    +    // [stopcallback.inplace.cons], constructors and destructor
    +    template<class C>
    +      explicit in_place_stop_callback(in_place_stop_token st, C&& cb)
    +        noexcept(is_nothrow_constructible_v<Callback, C>);
    +    ~in_place_stop_callback();
    +
    +    in_place_stop_callback(in_place_stop_callback&&) = delete;
    +
    +  private:
    +    Callback callback_;      // exposition only
    +  };
    +
    +  template<class Callback>
    +    in_place_stop_callback(in_place_stop_token, Callback)
    +      -> in_place_stop_callback<Callback>;
    +}
    +
    +
  2. +

    Mandates: in_place_stop_callback is instantiated with an argument for the template parameter Callback that satisfies both invocable and destructible.

    +
  3. +

    Preconditions: in_place_stop_callback is instantiated with an argument for the template parameter Callback that models both invocable and destructible.

    +
  4. +

    Recommended practice: Implementations should use the storage of the in_place_stop_callback objects to store the state necessary for their association with an in_place_stop_source object.

    +
+
10.1.7.2. Constructors and destructor [stopcallback.inplace.cons]
+
template<class C>
+  explicit in_place_stop_callback(in_place_stop_token st, C&& cb)
+    noexcept(is_nothrow_constructible_v<Callback, C>);
+
+
    +
  1. +

    Constraints: Callback and C satisfy constructible_from<Callback, C>.

    +
  2. +

    Preconditions: Callback and C model constructible_from<Callback, C>.

    +
  3. +

    Effects: Initializes callback_ with std::forward<C>(cb). +Any in_place_stop_source associated with st becomes associated with *this. +Registers ([stopsource.inplace.general]) the callback invocation std::forward<Callback>(callback_)() with the associated in_place_stop_source, if any. If the registration fails, evaluates +the callback invocation.

    +
  4. +

    Throws: Any exception thrown by the initialization of callback_.

    +
  5. +

    Remarks: If evaluating std::forward<Callback>(callback_)() exits via an exception, then terminate is invoked ([except.terminate]).

    +
+
~in_place_stop_callback();
+
+
    +
  1. +

    Effects: Unregisters ([stopsource.inplace.general]) the callback invocation from +the associated in_place_stop_source object, if any.

    +
  2. +

    Remarks: A program has undefined behavior if the start of this destructor does +not strongly happen before the start of the destructor of the associated in_place_stop_source object, if any.

    +
+

11. Execution control library [exec]

+

11.1. General [exec.general]

+
    +
  1. +

    This Clause describes components supporting execution of function objects +[function.objects].

    +
  2. +

    The following subclauses describe the requirements, concepts, and components +for execution control primitives as summarized in Table 1.

    +
+ + + + + + + + + +
Table N: Execution control library summary [tab:execution.summary]
+ Subclause + Header +
[exec.sched] + Schedulers + <execution> +
[exec.recv] + Receivers + +
[exec.opstate] + Operation states + +
[exec.snd] + Senders + +
[exec.execute] + One-way execution + +
+
    +
  1. +

    [Note: A large number of execution control primitives are +customization point objects. For an object one might define multiple types of +customization point objects, for which different rules apply. Table 2 shows +the types of customization point objects used in the execution control +library:

    +
+ + + + + + + + +
Table N+1: Types of customization point objects in the execution control library [tab:execution.cpos]
Customization point object type + Purpose + Examples +
core + provide core execution functionality, and connection between core components + connect, start, execute +
completion functions + called by senders to announce the completion of the work (success, error, or cancellation) + set_value, set_error, set_stopped +
senders + allow the specialization of the provided sender algorithms + +
    +
  • sender factories (schedule, just, read, ...) +
  • sender adaptors (transfer, then, let_value, ...) +
  • sender consumers (start_detached, sync_wait) +
+
queries + allow querying different properties of objects + +
    +
  • general queries (get_allocator, get_stop_token, ...) +
  • environment queries (get_scheduler, get_delegatee_scheduler, ...) +
  • scheduler queries (get_forward_progress_guarantee, execute_may_block_caller, ...) +
  • sender attribute queries (get_completion_scheduler) +
+
+

-- end note]

+
    +
  1. +

    This clause makes use of the following exposition-only entities:

    +
      +
    1. +
      template<class Fn, class... Args>
      +    requires callable<Fn, Args...>
      +  constexpr auto mandate-nothrow-call(Fn&& fn, Args&&... args) noexcept
      +    -> call-result-t<Fn, Args...> {
      +    return std::forward<Fn>(fn)(std::forward<Args>(args)...);
      +  }
      +
      +
        +
      • +

        Mandates: nothrow-callable<Fn, Args...> is true.

        +
      +
    2. +
      template<class T>
      +  concept movable-value =
      +    move_constructible<decay_t<T>> &&
      +    constructible_from<decay_t<T>, T> &&
      +    (!is_array_v<remove_cvref_t<T>>);
      +
      +
    3. +

      For function types F1 and F2 denoting R1(Args1...) and R2(Args2...) respectively, MATCHING-SIG(F1, F2) is true if and only if same_as<R1(Args&&...), R2(Args2&&...)> is true.

      +
    +
+

11.2. Queries and queryables [exec.queryable]

+

11.2.1. General [exec.queryable.general]

+
    +
  1. +

    A queryable object is a read-only collection of +key/value pairs where each key is a customization point object known as a query object. A query is an invocation of a query object with a queryable +object as its first argument and a (possibly empty) set of additional +arguments. The result of a query expression is valid as long as the +queryable object is valid. A query imposes syntactic +and semantic requirements on its invocations.

    +
  2. +

    Given a subexpression env that refers to a queryable object o, a query +object q, and a (possibly empty) pack of subexpressions args, the expression q(env, args...) is equal to +([concepts.equality]) the expression q(c, args...) where c is a const lvalue reference to o.

    +
  3. +

    The type of a query expression can not be void.

    +
  4. +

    The expression q(env, args...) is equality-preserving +([concepts.equality]) and does not modify the function object or the +arguments.

    +
  5. +

    If tag_invoke(q, env, args...) is well-formed, then q(env, args...) is expression-equivalent to tag_invoke(q, env, args...).

    +
  6. +

    Unless otherwise specified, the value returned by the expression q(env, args...) is valid as long as env is valid.

    +
+

11.2.2. queryable concept [exec.queryable.concept]

+
template<class T>
+  concept queryable = destructible<T>;
+
+
    +
  1. +

    The queryable concept specifies the constraints on the types of queryable +objects.

    +
  2. +

    Let env be an object of type Env. The type Env models queryable if for each +callable object q and a pack of subexpressions args, +if requires { q(env, args...) } is true then q(env, args...) meets any semantic requirements imposed by q.

    +
+

11.3. Asynchronous operations [async.ops]

+
    +
  1. +

    An execution resource is a program entity that manages +a (possibly dynamic) set of execution agents +([thread.req.lockable.general]), which it uses to execute parallel work on +behalf of callers. [Example 1: The currently active thread, a +system-provided thread pool, and uses of an API associated with an external +hardware accelerator are all examples of execution resources. -- end +example] Execution resources execute asynchronous operations. An execution +resource is either valid or invalid.

    +
  2. +

    An asynchronous operation is a distinct unit of +program execution that:

    +
      +
    • +

      is explicitly created;

      +
    • +

      can be explicitly started; an + asynchronous operation can be started once at most;

      +
    • +

      if started, eventually completes with a (possibly empty) set of result datums, and in exactly one of + three modes: success, failure, or cancellation, known as the + operation’s disposition; an asychronous + operation can only complete once; a successful completion, also known + as a value completion, can have an arbitrary + number of result datums; a failure completion, also known as an error completion, has a single result datum; a + cancellation completion, also known as a stopped + completion, has no result datum; an asynchronous operation’s async result is its disposition and its + (possibly empty) set of result datums.

      +
    • +

      can complete on a different execution resource than that on which it + started; and

      +
    • +

      can create and start other asychronous operations called child operations. A child operation is an + asynchronous operation that is created by the parent operation and, if + started, completes before the parent operation completes. A parent operation is the asynchronous operation that + created a particular child operation.

      +
    +

    An asynchronous operation can in fact execute +synchronously; that is, it can complete during the execution of its start +operation on the thread of execution that started it.

    +
  3. +

    An asynchronous operation has associated state known as its operation state.

    +
  4. +

    An asynchronous operation has an associated environment. An environment is a queryable object ([exec.queryable]) +representing the execution-time properties of the operation’s caller. The caller of an asynchronous operation is +its parent operation or the function that created it. An asynchronous +operation’s operation state owns the operation’s environment.

    +
  5. +

    An asynchronous operation has an associated receiver. A receiver is an aggregation of three handlers for the three +asynchronous completion dispositions: a value completion handler for a value +completion, an error completion handler for an error completion, and a +stopped completion handler for a stopped completion. A receiver has an +associated environment. An asynchronous operation’s operation state owns the +operation’s receiver. The environment of an asynchronous operation is equal +to its receiver’s environment.

    +
  6. +

    For each completion disposition, there is a completion +function. A completion function is a customization point object +([customization.point.object]) that accepts an asynchronous operation’s +receiver as the first argument and the result datums of the asynchronous +operation as additional arguments. The value completion function invokes the +receiver’s value completion handler with the value result datums; likewise +for the error completion function and the stopped completion function. A +completion function has an associated type known as its completion tag that names the unqualified type of the +completion function. A valid invocation of a completion function is called a completion operation.

    +
  7. +

    The lifetime of an +asynchronous operation, also known as the operation’s async lifetime, begins when its start operation begins +executing and ends when its completion operation begins executing. If the +lifetime of an asynchronous operation’s associated operation state ends +before the lifetime of the asynchronous operation, the behavior is +undefined. After an asynchronous operation executes a completion operation, +its associated operation state is invalid. Accessing any part of an invalid +operation state is undefined behavior.

    +
  8. +

    An asynchronous operation shall not execute a completion operation before its +start operation has begun executing. After its start operation has begun +executing, exactly one completion operation shall execute. The lifetime of an +asynchronous operation’s operation state can end during the execution of the +completion operation.

    +
  9. +

    A sender is a factory for one or more asynchronous +operations. Connecting a sender and a +receiver creates an asynchronous operation. The asynchronous operation’s +associated receiver is equal to the receiver used to create it, and its +associated environment is equal to the environment associated with the +receiver used to create it. The lifetime of an asynchronous operation’s +associated operation state does not depend on the lifetimes of either the +sender or the receiver from which it was created. A sender sends its results by way of the asynchronous operation(s) +it produces, and a receiver receives those results. A sender is either valid or invalid; it becomes invalid +when its parent sender (see below) becomes invalid.

    +
  10. +

    A scheduler is an abstraction of an execution +resource with a uniform, generic interface for scheduling work onto that +resource. It is a factory for senders whose asynchronous operations execute +value completion operations on an execution agent belonging to the +scheduler’s associated execution resource. A schedule-expression obtains such a sender from a +scheduler. A schedule sender is the result of a +schedule expression. On success, an asynchronous operation produced by a +schedule sender executes a value completion operation with an empty set of +result datums. Multiple schedulers can refer to the same execution resource. +A scheduler can be valid or invalid. A scheduler becomes invalid when the +execution resource to which it refers becomes invalid, as do any schedule +senders obtained from the scheduler, and any operation states obtained from +those senders.

    +
  11. +

    An asynchronous operation has one or more associated completion schedulers +for each of its possible dispositions. A completion +scheduler is a scheduler whose associated execution resource is used +to execute a completion operation for an asynchronous operation. A value +completion scheduler is a scheduler on which an asynchronous operation’s +value completion operation can execute. Likewise for error completion +schedulers and stopped completion schedulers.

    +
  12. +

    A sender has an associated queryable object ([exec.queryable]) known as its attributes that describes various characteristics of +the sender and of the asynchronous operation(s) it produces. For each +disposition, there is a query object for reading the associated completion +scheduler from a sender’s attributes; i.e., a value completion scheduler +query object for reading a sender’s value completion scheduler, etc. If a +completion scheduler query is well-formed, the returned completion scheduler +is unique for that disposition for any asynchronous operation the sender +creates. A schedule sender is required to have a value completion scheduler +attribute whose value is equal to the scheduler that produced the schedule +sender.

    +
  13. +

    A completion signature is a function type that +describes a completion operation. An asychronous operation has a finite set +of possible completion signatures corresponding to the completion operations +that the asynchronous operation potentially evaluates ([basic.def.odr]). For +a completion function set, receiver rcvr, and pack of arguments args, +let c be the completion operation set(rcvr, args...), and let F be the function type decltype(auto(set))(decltype((args))...). +A completion signature Sig is associated with c if and only if MATCHING-SIG(Sig, F) is true ([exec.general]). Together, +a sender type and an environment type Env determine the set of completion +signatures of an asynchronous operation that results from connecting the +sender with a receiver that has an environment of type Env. The type of the receiver does not affect an asychronous +operation’s completion signatures, only the type of the receiver’s +environment.

    +
  14. +

    A sender algorithm is a function that takes and/or +returns a sender. There are three categories of sender algorithms:

    +
      +
    • +

      A sender factory is a function that takes +non-senders as arguments and that returns a sender.

      +
    • +

      A sender adaptor is a function that constructs and +returns a parent sender from a set of one or more child senders and a +(possibly empty) set of additional arguments. An asynchronous operation +created by a parent sender is a parent to the +child operations created by the child +senders.

      +
    • +

      A sender consumer is a function that takes one or +more senders and a (possibly empty) set of additional arguments, and +whose return type is not the type of a sender.

      +
    +
+

11.4. Header <execution> synopsis [exec.syn]

+
namespace std {
+  // [exec.general], helper concepts
+  template<class T>
+    concept movable-value = see below; // exposition only
+
+  template<class From, class To>
+    concept decays-to = same_as<decay_t<From>, To>; // exposition only
+
+  template<class T>
+    concept class-type = decays-to<T, T> && is_class_v<T>;  // exposition only
+
+  // [exec.queryable], queryable objects
+  template<class T>
+    concept queryable = destructible;
+
+  // [exec.queries], queries
+  namespace queries { // exposition only
+    struct forwarding_query_t;
+    struct get_allocator_t;
+    struct get_stop_token_t;
+  }
+  using queries::forwarding_query_t;
+  using queries::get_allocator_t;
+  using queries::get_stop_token_t;
+  inline constexpr forwarding_query_t forwarding_query{};
+  inline constexpr get_allocator_t get_allocator{};
+  inline constexpr get_stop_token_t get_stop_token{};
+
+  template<class T>
+    using stop_token_of_t =
+      remove_cvref_t<decltype(get_stop_token(declval<T>()))>;
+
+  template<class T>
+    concept forwarding-query = // exposition only
+      forwarding_query(T{});
+}
+
+namespace std::execution {
+  // [exec.queries], queries
+  enum class forward_progress_guarantee;
+  namespace queries { // exposition only
+    struct get_domain_t;
+    struct get_scheduler_t;
+    struct get_delegatee_scheduler_t;
+    struct get_forward_progress_guarantee_t;
+    template<class CPO>
+      struct get_completion_scheduler_t;
+  }
+  using queries::get_domain_t;
+  using queries::get_scheduler_t;
+  using queries::get_delegatee_scheduler_t;
+  using queries::get_forward_progress_guarantee_t;
+  using queries::get_completion_scheduler_t;
+  inline constexpr get_domain_t get_domain{};
+  inline constexpr get_scheduler_t get_scheduler{};
+  inline constexpr get_delegatee_scheduler_t get_delegatee_scheduler{};
+  inline constexpr get_forward_progress_guarantee_t get_forward_progress_guarantee{};
+  template<class CPO>
+    inline constexpr get_completion_scheduler_t<CPO> get_completion_scheduler{};
+
+  namespace exec-envs { // exposition only
+    struct empty_env {};
+    struct get_env_t;
+  }
+  using envs-envs::empty_env;
+  using envs-envs::get_env_t;
+  inline constexpr get_env_t get_env {};
+
+  template<class T>
+    using env_of_t = decltype(get_env(declval<T>()));
+
+  // [exec.domain.default], execution domains
+  struct default_domain;
+
+  // [exec.sched], schedulers
+  template<class Sch>
+    concept scheduler = see below;
+
+  // [exec.recv], receivers
+  struct receiver_t {};
+
+  template<class Rcvr>
+    inline constexpr bool enable_receiver = see below;
+
+  template<class Rcvr>
+    concept receiver = see below;
+
+  template<class Rcvr, class Completions>
+    concept receiver_of = see below;
+
+  namespace receivers { // exposition only
+    struct set_value_t;
+    struct set_error_t;
+    struct set_stopped_t;
+  }
+  using receivers::set_value_t;
+  using receivers::set_error_t;
+  using receivers::set_stopped_t;
+  inline constexpr set_value_t set_value{};
+  inline constexpr set_error_t set_error{};
+  inline constexpr set_stopped_t set_stopped{};
+
+  // [exec.opstate], operation states
+  template<class O>
+    concept operation_state = see below;
+
+  namespace op-state { // exposition only
+    struct start_t;
+  }
+  using op-state::start_t;
+  inline constexpr start_t start{};
+
+  // [exec.snd], senders
+  struct sender_t {};
+
+  template<class Sndr>
+    inline constexpr bool enable_sender = see below;
+
+  template<class Sndr>
+    concept sender = see below;
+
+  template<class Sndr, class Env = empty_env>
+    concept sender_in = see below;
+
+  template<class Sndr, class Rcvr>
+    concept sender_to = see below;
+
+  template<class... Ts>
+    struct type-list; // exposition only
+
+  template<class Sndr, class Env = empty_env>
+    using single-sender-value-type = see below; // exposition only
+
+  template<class Sndr, class Env = empty_env>
+    concept single-sender = see below; // exposition only
+
+  // [exec.getcomplsigs], completion signatures
+  namespace completion-signatures { // exposition only
+    struct get_completion_signatures_t;
+  }
+  using completion-signatures::get_completion_signatures_t;
+  inline constexpr get_completion_signatures_t get_completion_signatures {};
+
+  template<class Sndr, class Env = empty_env>
+      requires sender_in<Sndr, Env>
+    using completion_signatures_of_t = call-result-t<get_completion_signatures_t, Sndr, Env>;
+
+  template<class... Ts>
+    using decayed-tuple = tuple<decay_t<Ts>...>; // exposition only
+
+  template<class... Ts>
+    using variant-or-empty = see below; // exposition only
+
+  template<class Sndr,
+           class Env = empty_env,
+           template<class...> class Tuple = decayed-tuple,
+           template<class...> class Variant = variant-or-empty>
+      requires sender_in<Sndr, Env>
+    using value_types_of_t = see below;
+
+  template<class Sndr,
+           class Env = empty_env,
+           template<class...> class Variant = variant-or-empty>
+      requires sender_in<Sndr, Env>
+    using error_types_of_t = see below;
+
+  template<class Sndr, class Env = empty_env>
+      requires sender_in<Sndr, Env>
+    inline constexpr bool sends_stopped = see below;
+
+  template <sender Sndr>
+    using tag_of_t = see below;
+
+  // [exec.snd.transform], sender transformations
+  template<class Domain, sender Sndr>
+    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndrv);
+
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env& env);
+
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+
+  // [exec.snd.apply], sender algorithm application
+  template<class Domain, class Tag, sender Sndr, class... Args>
+    constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+
+  // [exec.connect], the connect sender algorithm
+  namespace senders-connect { // exposition only
+    struct connect_t;
+  }
+  using senders-connect::connect_t;
+  inline constexpr connect_t connect{};
+
+  template<class Sndr, class Rcvr>
+    using connect_result_t = decltype(connect(declval<Sndr>(), declval<Rcvr>()));
+
+  // [exec.factories], sender factories
+  namespace sender-factories { // exposition only
+    struct just_t;
+    struct just_error_t;
+    struct just_stopped_t;
+    struct schedule_t;
+  }
+  inline constexpr just just{};
+  inline constexpr just_error_t just_error{};
+  inline constexpr just_stopped_t just_stopped{};
+  using sender-factories::schedule_t;
+  inline constexpr schedule_t schedule{};
+  inline constexpr unspecified read{};
+
+  template<scheduler Sndr>
+    using schedule_result_t = decltype(schedule(declval<Sndr>()));
+
+  // [exec.adapt], sender adaptors
+  namespace sender-adaptor-closure { // exposition only
+    template<class-type D>
+      struct sender_adaptor_closure { };
+  }
+  using sender-adaptor-closure::sender_adaptor_closure;
+
+  namespace sender-adaptors { // exposition only
+    struct on_t;
+    struct transfer_t;
+    struct schedule_from_t;
+    struct then_t;
+    struct upon_error_t;
+    struct upon_stopped_t;
+    struct let_value_t;
+    struct let_error_t;
+    struct let_stopped_t;
+    struct bulk_t;
+    struct split_t;
+    struct when_all_t;
+    struct when_all_with_variant_t;
+    struct into_variant_t;
+    struct stopped_as_optional_t;
+    struct stopped_as_error_t;
+    struct ensure_started_t;
+  }
+  using sender-adaptors::on_t;
+  using sender-adaptors::transfer_t;
+  using sender-adaptors::schedule_from_t;
+  using sender-adaptors::then_t;
+  using sender-adaptors::upon_error_t;
+  using sender-adaptors::upon_stopped_t;
+  using sender-adaptors::let_value_t;
+  using sender-adaptors::let_error_t;
+  using sender-adaptors::let_stopped_t;
+  using sender-adaptors::bulk_t;
+  using sender-adaptors::split_t;
+  using sender-adaptors::when_all_t;
+  using sender-adaptors::when_all_with_variant_t;
+  using sender-adaptors::into_variant_t;
+  using sender-adaptors::stopped_as_optional_t;
+  using sender-adaptors::stopped_as_error_t;
+  using sender-adaptors::ensure_started_t;
+
+  inline constexpr on_t on{};
+  inline constexpr transfer_t transfer{};
+  inline constexpr schedule_from_t schedule_from{};
+
+  inline constexpr then_t then{};
+  inline constexpr upon_error_t upon_error{};
+  inline constexpr upon_stopped_t upon_stopped{};
+
+  inline constexpr let_value_t let_value{};
+  inline constexpr let_error_t let_error{};
+  inline constexpr let_stopped_t let_stopped{};
+
+  inline constexpr bulk_t bulk{};
+
+  inline constexpr split_t split{};
+  inline constexpr when_all_t when_all{};
+  inline constexpr when_all_with_variant_t when_all_with_variant{};
+
+  inline constexpr into_variant_t into_variant{};
+
+  inline constexpr stopped_as_optional_t stopped_as_optional;
+
+  inline constexpr stopped_as_error_t stopped_as_error;
+
+  inline constexpr ensure_started_t ensure_started{};
+
+  // [exec.consumers], sender consumers
+  namespace sender-consumers { // exposition only
+    struct start_detached_t;
+  }
+  using sender-consumers::start_detached_t;
+  inline constexpr start_detached_t start_detached{};
+
+  // [exec.utils], sender and receiver utilities
+  // [exec.utils.rcvr.adptr]
+  template<
+      class-type Derived,
+      receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
+    class receiver_adaptor;
+
+  template<class Fn>
+    concept completion-signature = // exposition only
+      see below;
+
+  // [exec.utils.cmplsigs]
+  template<completion-signature... Fns>
+    struct completion_signatures {};
+
+  template<class... Args> // exposition only
+    using default-set-value =
+      completion_signatures<set_value_t(Args...)>;
+
+  template<class Err> // exposition only
+    using default-set-error =
+      completion_signatures<set_error_t(Err)>;
+
+  template<class Sigs> // exposition only
+    concept valid-completion-signatures = see below;
+
+  // [exec.utils.mkcmplsigs]
+  template<
+    valid-completion-signatures InputSignatures,
+    valid-completion-signatures AdditionalSignatures = completion_signatures<>,
+    template<class...> class SetValue = see below,
+    template<class> class SetError = see below,
+    valid-completion-signatures SetStopped = completion_signatures<set_stopped_t()>>
+  using transform_completion_signatures = completion_signatures<see below>;
+
+  template<
+    sender Sndr,
+    class Env = empty_env,
+    valid-completion-signatures AdditionalSignatures = completion_signatures<>,
+    template<class...> class SetValue = see below,
+    template<class> class SetError = see below,
+    valid-completion-signatures SetStopped = completion_signatures<set_stopped_t()>>
+      requires sender_in<Sndr, Env>
+  using transform_completion_signatures_of =
+    transform_completion_signatures<
+      completion_signatures_of_t<Sndr, Env>, AdditionalSignatures, SetValue, SetError, SetStopped>;
+
+  // [exec.ctx], execution resources
+  class run_loop;
+}
+
+namespace std::this_thread {
+  // [exec.queries], queries
+  namespace queries { // exposition only
+    struct execute_may_block_caller_t;
+  }
+  using queries::execute_may_block_caller_t;
+  inline constexpr execute_may_block_caller_t execute_may_block_caller{};
+
+  namespace this-thread { // exposition only
+    struct sync-wait-env; // exposition only
+    template<class Sndr>
+        requires sender_in<Sndr, sync-wait-env>
+      using sync-wait-type = see below; // exposition only
+    template<class Sndr>
+      using sync-wait-with-variant-type = see below; // exposition only
+
+    struct sync_wait_t;
+    struct sync_wait_with_variant_t;
+  }
+  using this-thread::sync_wait_t;
+  using this-thread::sync_wait_with_variant_t;
+  inline constexpr sync_wait_t sync_wait{};
+  inline constexpr sync_wait_with_variant_t sync_wait_with_variant{};
+}
+
+namespace std::execution {
+  // [exec.execute], one-way execution
+  namespace execute { // exposition only
+    struct execute_t;
+  }
+  using execute::execute_t;
+  inline constexpr execute_t execute{};
+
+  // [exec.as.awaitable]
+  namespace coro-utils { // exposition only
+    struct as_awaitable_t;
+  }
+  using coro-utils::as_awaitable_t;
+  inline constexpr as_awaitable_t as_awaitable;
+
+  // [exec.with.awaitable.senders]
+  template<class-type Promise>
+    struct with_awaitable_senders;
+}
+
+
    +
  1. +

    The exposition-only type variant-or-empty<Ts...> is + defined as follows:

    +
      +
    1. +

      If sizeof...(Ts) is greater than zero, variant-or-empty<Ts...> names the type variant<Us...> where Us... is the pack decay_t<Ts>... with +duplicate types removed.

      +
    2. +

      Otherwise, variant-or-empty<Ts...> names the +exposition-only class type:

      +
      struct empty-variant {
      +  empty-variant() = delete;
      +};
      +
      +
    +
+

11.5. Queries [exec.queries]

+

11.5.1. std::forwarding_query [exec.fwd.env]

+
    +
  1. +

    forwarding_query asks a query object whether it should be forwarded +through queryable adaptors.

    +
  2. +

    The name forwarding_query denotes a query object. For some query +object q of type Q, forwarding_query(q) is expression-equivalent +to:

    +
      +
    1. +

      mandate-nothrow-call(tag_invoke, forwarding_query, q) if that expression is well-formed.

      +
        +
      • +

        Mandates: The expression above has type bool and is a core +constant expressions if q is a core constant expression.

        +
      +
    2. +

      Otherwise, true if derived_from<Q, forwarding_query_t> is true.

      +
    3. +

      Otherwise, false.

      +
    +
+

11.5.2. std::get_allocator [exec.get.allocator]

+
    +
  1. +

    get_allocator asks an object for its associated allocator.

    +
  2. +

    The name get_allocator denotes a query object. For some subexpression env, get_allocator(env) is expression-equivalent to mandate-nothrow-call(tag_invoke, get_allocator, as_const(env)).

    +
      +
    • +

      Mandates: The type of the expression above +satisfies Allocator.

      +
    +
  3. +

    forwarding_query(get_allocator) is true.

    +
  4. +

    get_allocator() (with no arguments) is expression-equivalent to execution::read(get_allocator) ([exec.read]).

    +
+

11.5.3. std::get_stop_token [exec.get.stop.token]

+
    +
  1. +

    get_stop_token asks an object for an associated stop token.

    +
  2. +

    The name get_stop_token denotes a query object. For some subexpression env, get_stop_token(env) is expression-equivalent to:

    +
      +
    1. +

      mandate-nothrow-call(tag_invoke, get_stop_token, as_const(env)), if this expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above satisfies stoppable_token.

        +
      +
    2. +

      Otherwise, never_stop_token{}.

      +
    +
  3. +

    forwarding_query(get_stop_token) is a core constant +expression and has value true.

    +
  4. +

    get_stop_token() (with no arguments) is expression-equivalent to execution::read(get_stop_token) ([exec.read]).

    +
+

11.5.4. execution::get_env [exec.get.env]

+
    +
  1. +

    get_env is a customization point object. For some subexpression o of type O, get_env(o) is expression-equivalent to

    +
      +
    1. +

      tag_invoke(get_env, const_cast<const O&>(o)) if that expression is +well-formed.

      +
        +
      • +

        Mandates: The expression above is not potentially throwing, and +its type satisfies queryable ([exec.queryable]).

        +
      +
    2. +

      Otherwise, empty_env{}.

      +
    +
  2. +

    The value of get_env(o) shall be valid while o is valid.

    +
  3. +

    When passed a sender object, get_env returns the sender’s attributes. When +passed a receiver, get_env returns the receiver’s environment.

    +
+

11.5.5. execution::get_domain [exec.get.domain]

+
    +
  1. +

    get_domain asks an object for an associated execution domain tag.

    +
  2. +

    The name get_domain denotes a query object. For some subexpression env, get_domain(env) is expression-equivalent to mandate-nothrow-call(tag_invoke, get_domain, as_const(env)), +if this expression is well-formed.

    +
  3. +

    forwarding_query(execution::get_domain) is a core constant +expression and has value true.

    +
  4. +

    get_domain() (with no arguments) is expression-equivalent to execution::read(get_domain) ([exec.read]).

    +
+

11.5.6. execution::get_scheduler [exec.get.scheduler]

+
    +
  1. +

    get_scheduler asks an object for its associated scheduler.

    +
  2. +

    The name get_scheduler denotes a query object. For some +subexpression env, get_scheduler(env) is expression-equivalent to mandate-nothrow-call(tag_invoke, get_scheduler, as_const(env)).

    +
      +
    • +

      Mandates: The type of the expression above satisfies scheduler.

      +
    +
  3. +

    forwarding_query(execution::get_scheduler) is a core constant +expression and has value true.

    +
  4. +

    get_scheduler() (with no arguments) is expression-equivalent to execution::read(get_scheduler) ([exec.read]).

    +
+

11.5.7. execution::get_delegatee_scheduler [exec.get.delegatee.scheduler]

+
    +
  1. +

    get_delegatee_scheduler asks an object for a scheduler that can be used to delegate work to for the purpose of forward progress delegation.

    +
  2. +

    The name get_delegatee_scheduler denotes a query object. For some +subexpression env, get_delegatee_scheduler(env) is expression-equivalent to mandate-nothrow-call(tag_invoke, get_delegatee_scheduler, as_const(env)).

    +
      +
    • +

      Mandates: The type of the expression above is satisfies scheduler.

      +
    +
  3. +

    forwarding_query(execution::get_delegatee_scheduler) is a core +constant expression and has value true.

    +
  4. +

    get_delegatee_scheduler() (with no arguments) is expression-equivalent to execution::read(get_delegatee_scheduler) ([exec.read]).

    +
+

11.5.8. execution::get_forward_progress_guarantee [exec.get.forward.progress.guarantee]

+
enum class forward_progress_guarantee {
+  concurrent,
+  parallel,
+  weakly_parallel
+};
+
+
    +
  1. +

    get_forward_progress_guarantee asks a scheduler about the forward progress guarantees of execution agents created by that scheduler.

    +
  2. +

    The name get_forward_progress_guarantee denotes a query object. For some subexpression sch, let Sch be decltype((sch)). If Sch does not satisfy scheduler, get_forward_progress_guarantee is ill-formed. +Otherwise, get_forward_progress_guarantee(sch) is expression-equivalent to:

    +
      +
    1. +

      mandate-nothrow-call(tag_invoke, get_forward_progress_guarantee, as_const(sch)), if this expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above is forward_progress_guarantee.

        +
      +
    2. +

      Otherwise, forward_progress_guarantee::weakly_parallel.

      +
    +
  3. +

    If get_forward_progress_guarantee(sch) for some scheduler sch returns forward_progress_guarantee::concurrent, all execution agents created by that scheduler shall provide the concurrent forward progress guarantee. If it returns forward_progress_guarantee::parallel, all execution agents created by that scheduler shall provide at least the parallel forward progress guarantee.

    +
+

11.5.9. this_thread::execute_may_block_caller [exec.execute.may.block.caller]

+
    +
  1. +

    this_thread::execute_may_block_caller asks a scheduler sch whether a call execute(sch, f) with any invocable f may block the thread where such a call occurs.

    +
  2. +

    The name this_thread::execute_may_block_caller denotes a query object. For some subexpression sch, let Sch be decltype((sch)). If Sch does not satisfy scheduler, this_thread::execute_may_block_caller is ill-formed. Otherwise, this_thread::execute_may_block_caller(sch) is expression-equivalent to:

    +
      +
    1. +

      mandate-nothrow-call(tag_invoke, this_thread::execute_may_block_caller, as_const(sch)), if this expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above is bool.

        +
      +
    2. +

      Otherwise, true.

      +
    +
  3. +

    If this_thread::execute_may_block_caller(sch) for some scheduler sch returns false, no execute(sch, f) call with some invocable f shall block the calling thread.

    +
+

11.5.10. execution::get_completion_scheduler [exec.completion.scheduler]

+
    +
  1. +

    get_completion_scheduler<completion-tag> obtains the +completion scheduler associated with a completion tag from a sender’s +attributes.

    +
  2. +

    The name get_completion_scheduler denotes a query object template. For some +subexpression q, let Q be decltype((q)). If the template argument Tag in get_completion_scheduler<Tag>(q) is not one of set_value_t, set_error_t, or set_stopped_t, get_completion_scheduler<Tag>(q) is +ill-formed. Otherwise, get_completion_scheduler<Tag>(q) is +expression-equivalent to mandate-nothrow-call(tag_invoke, get_completion_scheduler<Tag>, as_const(q)) if this expression is +well-formed.

    +
      +
    • +

      Mandates: The type of the expression above satisfies scheduler.

      +
    +
  3. +

    If, for some sender sndr and completion function C that has an associated +completion tag Tag, get_completion_scheduler<Tag>(get_env(sndr)) is +well-formed and results in a scheduler sch, and the sender sndr invokes C(rcvr, args...), for some receiver rcvr that has been connected to sndr, with +additional arguments args..., on an execution agent that does not +belong to the associated execution resource of sch, the behavior is +undefined.

    +
  4. +

    The expression forwarding_query(get_completion_scheduler<CPO>) is a core constant expression and has value true.

    +
+

11.6. Schedulers [exec.sched]

+
    +
  1. +

    The scheduler concept defines the requirements of a scheduler type +([async.ops]). schedule is a customization point object that accepts a +scheduler. A valid invocation of schedule is a schedule-expression.

    +
    template<class Sch>
    +  concept scheduler =
    +    queryable<Sch> &&
    +    requires(Sch&& sch, const get_completion_scheduler_t<set_value_t> tag) {
    +      { schedule(std::forward<Sch>(sch)) } -> sender;
    +      { tag_invoke(tag, get_env(
    +          schedule(std::forward<Sch>(sch)))) } -> same_as<remove_cvref_t<Sch>>;
    +    } &&
    +    equality_comparable<remove_cvref_t<Sch>> &&
    +    copy_constructible<remove_cvref_t<Sch>>;
    +
    +
  2. +

    Let Sch be the type of a scheduler and let Env be the type of an execution +environment for which sender_in<schedule_result_t<Sch>, Env> is true. Then sender-of-in<schedule_result_t<Sch>, Env> shall be true.

    +
  3. +

    None of a scheduler’s copy constructor, destructor, equality comparison, or swap member functions shall exit via an exception.

    +
  4. +

    None of these member functions, nor a scheduler type’s schedule function, +shall introduce data races as a result of concurrent invocations of those +functions from different threads.

    +
  5. +

    For any two (possibly const) values sch1 and sch2 of some scheduler type Sch, sch1 == sch2 shall return true only if both sch1 and sch2 share the +same associated execution resource.

    +
  6. +

    For a given scheduler expression sch, the expression get_completion_scheduler<set_value_t>(get_env(schedule(sch))) shall +compare equal to sch.

    +
  7. +

    For a given scheduler expression sch, if the expression get_domain(sch) is well-formed, then the expression get_domain(get_env(schedule(sch))) is also well-formed and has the same type.

    +
  8. +

    A scheduler type’s destructor shall not block pending completion of any +receivers connected to the sender objects returned from schedule. The ability to wait for completion of submitted function +objects can be provided by the associated execution resource of the +scheduler.

    +
+

11.7. Receivers [exec.recv]

+

11.7.1. Receiver concepts [exec.recv.concepts]

+
    +
  1. +

    A receiver represents the continuation of an asynchronous operation. The receiver concept defines the requirements for a receiver type +([async.ops]). The receiver_of concept defines the requirements for a +receiver type that is usable as the first argument of a set of completion +operations corresponding to a set of completion signatures. The get_env customization point is used to access a receiver’s associated environment.

    +
    template<class Rcvr>
    +  concept is-receiver = // exposition only
    +    derived_from<typename Rcvr::receiver_concept, receiver_t>;
    +
    +template<class Rcvr>
    +  inline constexpr bool enable_receiver = is-receiver<Rcvr>;
    +
    +template<class Rcvr>
    +  concept receiver =
    +    enable_receiver<remove_cvref_t<Rcvr>> &&
    +    requires(const remove_cvref_t<Rcvr>& rcvr) {
    +      { get_env(rcvr) } -> queryable;
    +    } &&
    +    move_constructible<remove_cvref_t<Rcvr>> &&  // rvalues are movable, and
    +    constructible_from<remove_cvref_t<Rcvr>, Rcvr>; // lvalues are copyable
    +
    +template<class Signature, class Rcvr>
    +  concept valid-completion-for = // exposition only
    +    requires (Signature* sig) {
    +      []<class Tag, class... Args>(Tag(*)(Args...))
    +          requires callable<Tag, remove_cvref_t<Rcvr>, Args...>
    +      {}(sig);
    +    };
    +
    +template<class Rcvr, class Completions>
    +  concept receiver_of =
    +    receiver<Rcvr> &&
    +    requires (Completions* completions) {
    +      []<valid-completion-for<Rcvr>...Sigs>(completion_signatures<Sigs...>*)
    +      {}(completions);
    +    };
    +
    +
  2. +

    Remarks: Pursuant to [namespace.std], users can specialize enable_receiver to true for cv-unqualified program-defined types that model receiver, and false for types that do not. Such specializations shall be usable in constant +expressions ([expr.const]) and have type const bool.

    +
  3. +

    Let rcvr be a receiver and let op_state be an operation state associated +with an asynchronous operation created by connecting rcvr with a sender. Let token be a stop token equal to get_stop_token(get_env(rcvr)). token shall +remain valid for the duration of the asynchronous operation’s lifetime +([async.ops]). This means that, unless it knows about +further guarantees provided by the type of receiver rcvr, the implementation +of op_state can not use token after it executes a completion operation. +This also implies that any stop callbacks registered on token must be +destroyed before the invocation of the completion operation.

    +
+

11.7.2. execution::set_value [exec.set.value]

+
    +
  1. +

    set_value is a value completion function ([async.ops]). Its associated +completion tag is set_value_t. The expression set_value(rcvr, vs...) for +some subexpression rcvr and pack of subexpressions vs is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is expression-equivalent to mandate-nothrow-call(tag_invoke, set_value, rcvr, vs...).

    +
+

11.7.3. execution::set_error [exec.set.error]

+
    +
  1. +

    set_error is an error completion function. Its associated completion tag is set_error_t. The expression set_error(rcvr, err) for some subexpressions rcvr and err is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is +expression-equivalent to mandate-nothrow-call(tag_invoke, set_error, rcvr, err).

    +
+

11.7.4. execution::set_stopped [exec.set.stopped]

+
    +
  1. +

    set_stopped is a stopped completion function. Its associated completion tag +is set_stopped_t. The expression set_stopped(rcvr) for some subexpression rcvr is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is +expression-equivalent to mandate-nothrow-call(tag_invoke, set_stopped, rcvr).

    +
+

11.8. Operation states [exec.opstate]

+
    +
  1. +

    The operation_state concept defines the requirements of an operation state +type ([async.ops]).

    +
    template<class O>
    +  concept operation_state =
    +    queryable<O> &&
    +    is_object_v<O> &&
    +    requires (O& o) {
    +      { start(o) } noexcept;
    +    };
    +
    +
  2. +

    If an operation_state object is moved during the lifetime of its +asynchronous operation ([async.ops]), the behavior is undefined.

    +
  3. +

    Library-provided operation state types are non-movable.

    +
+

11.8.1. execution::start [exec.opstate.start]

+
    +
  1. +

    The name start denotes a customization point object that starts +([async.ops]) the asynchronous operation associated with the operation state +object. The expression start(O) for some subexpression O is ill-formed +if O is an rvalue. Otherwise, it is expression-equivalent to:

    +
    mandate-nothrow-call(tag_invoke, start, O)
    +
    +
  2. +

    If the function selected by tag_invoke does not start the asynchronous +operation associated with the operation state O, the behavior of calling start(O) is undefined.

    +
+

11.9. Senders [exec.snd]

+

11.9.1. General [exec.snd.general]

+
    +
  1. +

    For the purposes of this subclause, a sender is an object that satisfies the sender concept ([async.ops]).

    +
  2. +

    Subclauses [exec.factories] and [exec.adapt] define customizable algorithms +that return senders. Each algorithm has a default implementation. Let sndr be the result of an invocation of such an algorithm or an object equal to +such ([concepts.equality]), and let Sndr be decltype((sndr)). Let rcvr be a receiver with associated environment env of type Env such that sender_in<Sndr, Env> is true. For the default implementation of the +algorithm that produced sndr, connecting sndr to rcvr and starting the +resulting operation state ([async.ops]) necessarily results in the potential +evaluation ([basic.def.odr]) of a set of completion operations whose first +argument is a subexpression equal to rcvr. Let Sigs be a pack of +completion signatures corresponding to this set of completion operations. +Then the type of the expression get_completion_signatures(sndr, env) is a +specialization of the class template completion_signatures, +([exec.utils.cmplsigs]) the set of whose template arguments is Sigs. If a +user-provided implementation of the algorithm that produced sndr is +selected instead of the default, any completion signature that is in the set +of types denoted by completion_signatures_of_t<Sndr, Env> and that is not +part of Sigs shall correspond to error or stopped completion operations, +unless otherwise specified.

    +
  3. +

    This subclause makes use of the following exposition-only entities.

    +
      +
    1. +

      For a queryable object env, let FWD-ENV(env) be a +queryable object such that for a query object q and a pack of +subexpressions as, the expression tag_invoke(q, FWD-ENV(env), as...) is ill-formed if forwarding_query(q) is false; +otherwise, it is expression-equivalent to tag_invoke(q, env, as...).

      +
    2. +

      For a query object q and a subexpression v, let MAKE-ENV(q, v) be a queryable object env such that +the result of tag_invoke(q, env) has a value equal to v ([concepts.equality]). Unless otherwise stated, the object to which tag_invoke(q, env) refers remains valid while env remains valid.

      +
    3. +

      For two queryable objects env1 and env2, a query object q and a +pack of subexpressions as, let JOIN-ENV(env1, env2) be a queryable object env3 such that tag_invoke(q, env3, as...) is expression-equivalent to:

      +
        +
      • +

        tag_invoke(q, env1, as...) if that expression is well-formed,

        +
      • +

        otherwise, tag_invoke(q, env2, as...) if that expression is + well-formed,

        +
      • +

        otherwise, tag_invoke(q, env3, as...) is ill-formed.

        +
      +
    4. +

      The expansions of FWD-ENV, MAKE-ENV, and JOIN-ENV can be context-dependent; i.e., they can expand to +expressions with different types and value categories in different +contexts for the same arguments.

      +
    5. +

      For a scheduler sch, let SCHED-ATTRS(sch) be a +queryable object o1 such that tag_invoke(get_completion_scheduler<Tag>, o1) is a +prvalue with the same type and value as sch where Tag is one +of set_value_t or set_stopped_t; and let tag_invoke(get_domain, o1) be expression-equivalent to tag_invoke(get_domain, sch). Let SCHED-ENV(sch) be a queryable object o2 such that tag_invoke(get_scheduler, o2) is a prvalue with the same +type and value as sch, and let tag_invoke(get_domain, o2) be expression-equivalent to tag_invoke(get_domain, sch).

      +
    6. +

      For two subexpressions rcvr and expr, let SET-VALUE(rcvr, expr) be (expr, set_value(rcvr)) if the type of expr is void; +otherwise, it is set_value(rcvr, expr). Let TRY-EVAL(rcvr, expr) be:

      +
      try {
      +  expr;
      +} catch(...) {
      +  set_error(rcvr, current_exception());
      +}
      +
      +

      if expr is potentially-throwing; otherwise, expr. Let TRY-SET-VALUE(rcvr, expr) be TRY-EVAL(rcvr, SET-VALUE(rcvr, expr)) except that rcvr is evaluated only once.

      +
    7. +
      template<class Default = default_domain, class Sndr>
      +constexpr auto completion-domain(const Sndr& sndr) noexcept;
      +
      +
        +
      1. +

        Effects: Let COMPL-DOMAIN(T) be the type of the expression get_domain(get_completion_scheduler<T>(get_env(sndr))). If COMPL-DOMAIN(set_value_t), COMPL-DOMAIN(set_error_t), and COMPL-DOMAIN(set_stopped_t) all share a common type +[meta.trans.other] (ignoring those types that are ill-formed), then completion-domain<Default>(sndr) is a default-constructed +prvalue of that type. +Otherwise, if all of those types are ill-formed, completion-domain<Default>(sndr) is a default-constructed +prvalue of type Default. +Otherwise, completion-domain<Default>(sndr) is ill-formed.

        +
      +
    8. +
      template<class Tag, class Env, class Default>
      +constexpr decltype(auto) query-with-default(Tag, const Env& env, Default&& value) noexcept(see below);
      +
      +
        +
      1. +

        Effects: Equivalent to:

        +
          +
        • +

          return Tag()(env); if that expression is well-formed,

          +
        • +

          return static_cast<Default>(std::forward<Default>(value)); otherwise.

          +
        +
      2. +

        Remarks: The expression in the noexcept clause is:

        +
        is_invocable_v<Tag, const Env&> ? is_nothrow_invocable_v<Tag, const Env&>
        +                                : is_nothrow_constructible_v<Default, Default>
        +
        +
      +
    9. +
      template<class Sndr>
      +constexpr auto get-domain-early(const Sndr& sndr) noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to return Domain(); where Domain is the decayed type of the first of the following +expressions that is well-formed:

        +
          +
        • +

          get_domain(get_env(sndr))

          +
        • +

          completion-domain(sndr)

          +
        • +

          default_domain()

          +
        +
      +
    10. +
      template<class Sndr, class Env>
      +constexpr auto get-domain-late(const Sndr& sndr, const Env& env) noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to:

        +
          +
        • +

          If sender-for<Sndr, transfer_t> is true, +then return Domain(); where Domain is +the type of the following expression:

          +
          [] {
          +  auto [ignore1, sch, ignore2] = sndr;
          +  return query-or-default(get_domain, sch, default_domain());
          +}();
          +
          +
        • +

          Otherwise, return Domain(); where Domain is +the first of the following expressions that is well-formed and has class +type:

          +
            +
          • +

            get_domain(get_env(sndr))

            +
          • +

            completion-domain<void>(sndr)

            +
          • +

            get_domain(env)

            +
          • +

            get_domain(get_scheduler(env))

            +
          • +

            default_domain().

            +
          +
        +

        The transfer algorithm is unique in that it ignores the +execution domain of its predecessor, using only the domain of its +destination scheduler to select a customization.

        +
      +
    11. +
      template<callable Fun>
      +  requires is_nothrow_move_constructible_v<Fun>
      +struct emplace-from { // exposition only
      +  Fun fun; // exposition only
      +  using type = call-result-t<Fun>;
      +
      +  constexpr operator type() && noexcept(nothrow-callable<Fun>) {
      +    return std::move(fun)();
      +  }
      +
      +  constexpr type operator()() && noexcept(nothrow-callable<Fun>) {
      +    return std::move(fun)();
      +  }
      +};
      +
      +
        +
      1. +

        emplace-from is used to emplace +non-movable types into containers like tuple, optional, and variant.

        +
      +
    12. +
      struct on-stop-request {
      +  in_place_stop_source& stop_src;
      +  void operator()() noexcept { stop_src.request_stop(); }
      +};
      +
      +
    13. +
      template<class... T>
      +struct product-type {
      +  using type0 = T0;      // exposition only
      +  using type1 = T1;      // exposition only
      +    ...
      +  using typen-1 = Tn-1;   // exposition only
      +
      +  T0 t0;      // exposition only
      +  T1 t1;      // exposition only
      +    ...
      +  Tn-1 tn-1;   // exposition only
      +};
      +
      +
        +
      1. +

        An expression of type product-type is usable as the initializer of a +structured binding declaration [dcl.struct.bind].

        +
      +
    14. +
      template <semiregular Tag, movable-value Data = see below, sender... Child>
      +constexpr auto make-sender(Tag, Data&& data, Child&&... child);
      +
      +
        +
      1. +

        Remarks: The default template argument for the Data template parameter +denotes an unspecified empty trivial class type.

        +
      2. +

        Returns: A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> where the tag member has been default-initialized and the data and childn... members have +been direct initialized from their respective forwarded arguments, where basic-sender is the following exposition-only class template +except as noted below:

        +
        template<class T, class... Us>
        +concept one-of = (same_as<T, Us> ||...); // exposition only
        +
        +template<class Tag>
        +concept completion-tag = // exposition only
        +  one-of<Tag, set_value_t, set_error_t, set_stopped_t>;
        +
        +template<template<class...> class T, class... Args>
        +concept well-formed = requires { typename T<Args...>; }; // exposition only
        +
        +template<const auto& Fun, class... Args>
        +concept cpo-callable = callable<decltype(Fun), Args...>; // exposition only
        +
        +template<const auto& Fun, class... Args>
        +using cpo-result-t = call-result-t<decltype(Fun), Args...>; // exposition only
        +
        +struct default-impls {  // exposition only
        +  static constexpr auto get-attrs = see below;
        +  static constexpr auto get-env = see below;
        +  static constexpr auto get-state = see below;
        +  static constexpr auto start = see below;
        +  static constexpr auto complete = see below;
        +};
        +
        +template<class Tag>
        +struct impls-for : default-impls {}; // exposition only
        +
        +template<class Sndr, class Rcvr> // exposition only
        +using state-type = decay_t<cpo-result-t<
        +  impls-for<tag_of_t<Sndr>>::get-state, Sndr, Rcvr&>>;
        +
        +template<class Index, class Sndr, class Rcvr> // exposition only
        +using env-type = cpo-result-t<
        +  impls-for<tag_of_t<Sndr>>::get-env, Index,
        +  state-type<Sndr, Rcvr>&, const Rcvr&>>;
        +
        +template<class Sndr, class Rcvr, class Index>  // arguments are not associated entities ([lib.tmpl-heads])
        +  requires well-formed<env-type, Index, Sndr, Rcvr>
        +struct basic-receiver {  // exposition only
        +  using tag_t = tag_of_t<Sndr>; // exposition only
        +  using receiver_concept = receiver_t;
        +
        +  template<completion-tag Tag, class... Args>
        +    requires cpo-callable<impls-for<tag_t>::complete,
        +      Index, state-type<Sndr, Rcvr>&, Rcvr&, Tag, Args...>
        +  friend void tag_invoke(Tag, basic-receiver&& self, Args&&... args) noexcept {
        +    (void) impls-for<tag_t>::complete(
        +      Index(), self.op_->state_, self.op_->rcvr_, Tag(), std::forward<Args>(args)...);
        +  }
        +
        +  template<same_as<get_env_t> Tag>
        +  friend auto tag_invoke(Tag, const basic-receiver& self) noexcept
        +    -> env-type<Index, Sndr, Rcvr> {
        +    const auto& rcvr = self.op_->rcvr_;
        +    return impls-for<tag_t>::get-env(Index(), self.op_->state_, rcvr);
        +  }
        +
        +  basic-operation<Sndr, Rcvr>* op_; // exposition only
        +};
        +
        +constexpr auto connect-all =   // exposition only
        +  []<class Sndr, class Rcvr, size_t... Is>(
        +    basic-operation<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>)
        +      noexcept( TODO ) requires ( TODO ) {
        +      auto&& [ign1, ign2, ...child] = std::forward<Sndr>(sndr);
        +      return product-type{connect(
        +        std::forward_like<Sndr>(child),
        +        basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
        +    };
        +
        +template<class Sndr>
        +using indices-for = make_index_sequence<tuple_size_v<Sndr>-2>; // exposition only
        +
        +template<class Sndr, class Rcvr>
        +using inner-ops-tuple =   // exposition only
        +  cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr,
        +    indices-for<Sndr>>;
        +
        +template<class Sndr, class Rcvr> // arguments are not associated entities ([lib.tmpl-heads])
        +  requires well-formed<state-type, Sndr, Rcvr> &&
        +    well-formed<inner-ops-tuple, Sndr, Rcvr>
        +struct basic-operation {  // exposition only
        +  using tag_t = tag_of_t<Sndr>; // exposition only
        +
        +  Rcvr rcvr_; // exposition only
        +  state-type<Sndr, Rcvr> state_; // exposition only
        +  inner-ops-tuple<Sndr, Rcvr> inner_ops_; // exposition only
        +
        +  basic-operation(Sndr&& sndr, Rcvr rcvr)  // exposition only
        +    : rcvr_(std::move(rcvr))
        +    , state_(impls-for<tag_t>::get-state(std::forward<Sndr>(sndr), rcvr_))
        +    , inner_ops_(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
        +  {}
        +
        +  friend void tag_invoke(start_t, basic-operation& self) noexcept {
        +    auto& [...ops] = self.inner_ops_;
        +    impls-for<tag_t>::start(self.state_, self.rcvr_, ops...);
        +  }
        +};
        +
        +template<class Sndr, class Env>
        +using completion-signatures-for =  see below; // exposition only
        +
        +template<class Tag, class Data, class... Child> // arguments are not associated entities ([lib.tmpl-heads])
        +struct basic-sender {  // exposition only
        +  using sender_concept = sender_t;
        +
        +  template<same_as<get_env_t> GetEnvTag>
        +  friend decltype(auto) tag_invoke(GetEnvTag, const basic-sender& self) noexcept {
        +    return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
        +  }
        +
        +  template<same_as<connect_t> ConnectTag,
        +           decays-to<basic-sender> Self, receiver Rcvr>
        +  friend auto tag_invoke(ConnectTag, Self&& self, Rcvr rcvr)
        +    -> basic-operation<Self, Rcvr> {
        +    return {std::forward<Self>(self), std::move(rcvr)};
        +  }
        +
        +  template<same_as<get_completion_signatures_t> GetComplSigsTag,
        +           decays-to<basic-sender> Self, class Env>
        +  friend auto tag_invoke(GetComplSigsTag, Self&& self, Env&& env) noexcept
        +    -> completion-signatures-for<Self, Env> {
        +    return {};
        +  }
        +
        +  Tag tag;            // exposition only
        +  Data data;          // exposition only
        +  Child0 child0;      // exposition only
        +  Child1 child1;      // exposition only
        +    ...
        +  Childn-1 childn-1;   // exposition only
        +};
        +
        +template <class Sndr>
        +using data-type = decltype((declval<Sndr>().data)); // exposition only
        +
        +template <class Sndr, size_t N = 0>
        +using child-type = decltype((declval<Sndr>().childN)); // exposition only
        +
        +
      3. +

        It is unspecified whether instances of basic-sender can be +aggregate initialized.

        +
      4. +

        An expression of type basic-sender is usable as the +initializer of a structured binding declaration +[dcl.struct.bind].

        +
      5. +

        The member default-impls::get-attrs is initialized +with a callable object equivalent to the following lambda:

        +
        [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
        +  if constexpr (sizeof...(child) == 1)
        +    return FWD-ENV(get_env(child...)); //
        +  else
        +    return empty_env();
        +}
        +
        +
      6. +

        The member default-impls::get-env is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept
        +  -> decltype(FWD-ENV(get_env(rcvr))) {
        +  return FWD-ENV(get_env(rcvr));
        +}
        +
        +
      7. +

        The member default-impls::get-state is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept -> decltype(auto) {
        +  return get<1>(std::forward<Sndr>(sndr));
        +}
        +
        +
      8. +

        The member default-impls::start is initialized +with a callable object equivalent to the following lambda:

        +
        [](auto& state, auto& rcvr, auto&... ops) noexcept -> void {
        +  (execution::start(ops), ...);
        +}
        +
        +
      9. +

        The member default-impls::complete is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Index, class Rcvr, class Tag, class... Args>(
        +  Index, auto& state, Rcvr& rcvr, Tag, Args&&... args) noexcept
        +    -> void requires callable<Tag, Rcvr, Args...> {
        +  // Mandates: Index::value == 0
        +  Tag()(std::move(rcvr), std::forward<Args>(args)...);
        +}
        +
        +
      10. +

        For a subexpression sndr let Sndr be decltype((sndr)). Let rcvr be a receiver that has an associated environment of type Env such that sender_in<Sndr, Env> is true. completion-signatures-for<Sndr, Env> denotes +a specialization of completion_signatures, the set of whose +template arguments correspond to the set of completion operations +that are potentially evaluated as a result of calling start on the +operation state that results from connecting sndr and rcvr. When sender_in<Sndr, Env> is false, the type denoted by completion-signatures-for<Sndr, Env>, if any, +is not a specialization of completion_signatures.

        +

        Recommended practice: When sender_in<Sndr, Env> is false, +implementations are encouraged to use the type denoted by completion-signatures-for<Sndr, Env> to +communicate to users why.

        +
      +
    +
+

11.9.2. Sender concepts [exec.snd.concepts]

+
    +
  1. +

    The sender concept defines the requirements for a sender type +([async.ops]). The sender_in concept defines the requirements for a sender +type that can create asynchronous operations given an associated environment +type. The sender_to concept defines the requirements for a sender type +that can connect with a specific receiver type. The get_env customization +point object is used to access a sender’s associated attributes. The connect customization point object is used to connect ([async.ops]) a +sender and a receiver to produce an operation state.

    +
    template<class Sigs>
    +  concept valid-completion-signatures = see below; // exposition only
    +
    +template<class Sndr>
    +  concept is-sender = // exposition only
    +    derived_from<typename Sndr::sender_concept, sender_t>;
    +
    +template<class Sndr>
    +  inline constexpr bool enable_sender = is-sender<Sndr>;
    +
    +template<is-awaitable<env-promise<empty_env>> Sndr> // [exec.awaitables]
    +  inline constexpr bool enable_sender<Sndr> = true;
    +
    +template<class Sndr>
    +  concept sender =
    +    enable_sender<remove_cvref_t<Sndr>> &&
    +    requires (const remove_cvref_t<Sndr>& sndr) {
    +      { get_env(sndr) } -> queryable;
    +    } &&
    +    move_constructible<remove_cvref_t<Sndr>> &&  // rvalues are movable, and
    +    constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable
    +
    +template<class Sndr, class Env = empty_env>
    +  concept sender_in =
    +    sender<Sndr> &&
    +    queryable<Env> &&
    +    requires (Sndr&& sndr, Env&& env) {
    +      { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) } ->
    +        valid-completion-signatures;
    +    };
    +
    +template<class Sndr, class Rcvr>
    +  concept sender_to =
    +    sender_in<Sndr, env_of_t<Rcvr>> &&
    +    receiver_of<Rcvr, completion_signatures_of_t<Sndr, env_of_t<Rcvr>>> &&
    +    requires (Sndr&& sndr, Rcvr&& rcvr) {
    +      connect(std::forward<Sndr>(sndr), std::forward<Rcvr>(rcvr));
    +    };
    +
    +
  2. +

    Given a subexpression sndr, let Sndr be decltype((sndr)), let Env be +the type of an environment, and let rcvr be a receiver with an associated +environment Env. A completion operation is a permissible completion for Sndr and Env if its +completion signature appears in the argument list of the specialization of completion_signatures denoted by completion_signatures_of_t<Sndr, Env>. Sndr and Env model sender_in<Sndr, Env> if all the completion +operations that are potentially evaluated by connecting sndr to rcvr and +starting the resulting operation state are permissible completions for Sndr and Env.

    +
  3. +

    A type Sigs satisfies and models the exposition-only concept valid-completion-signatures if it denotes a specialization +of the completion_signatures class template.

    +
  4. +

    Remarks: Pursuant to [namespace.std], users can specialize enable_sender to true for cv-unqualified program-defined types that model sender, and false for types that do not. Such specializations shall be usable in constant +expressions ([expr.const]) and have type const bool.

    +
  5. +

    The exposition-only concepts sender-of and sender-of-in define the requirements for a sender +type that completes with a given unique set of value result types.

    +
    template<class... As>
    +  using value-signature = set_value_t(As...); // exposition only
    +
    +template<class Sndr, class Env, class... Values>
    +  concept sender-of-in =
    +    sender_in<Sndr, Env> &&
    +    MATCHING-SIG( // see [exec.general]
    +      set_value_t(Values...),
    +      value_types_of_t<Sndr, Env, value-signature, type_identity_t>);
    +
    +template<class Sndr, class... Values>
    +  concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
    +
    +
  6. +

    Let sndr be an expression such that decltype((sndr)) is Sndr. The type tag_of_t<Sndr> is as follows:

    +
      +
    • +

      If the declaration auto&& [tag, data, ...children] = sndr; would be +well-formed, tag_of_t<Sndr> is an alias for decltype(auto(tag)).

      +
    • +

      Otherwise, tag_of_t<Sndr> is ill-formed.

      +
    +
    There is no way in standard C++ to determine whether the above declaration +is well-formed without causing a hard error, so this presumes compiler +magic. However, the author anticipates the adoption of [@P2141R1], which +makes it possible to implement this purely in the library. P2141 has already +been approved by EWG for C++26.
    +
  7. +

    Let sender-for be an exposition-only concept defined as follows:

    +
    template<class Sndr, class Tag>
    +concept sender-for =
    +  sender<Sndr> &&
    +  same_as<tag_of_t<Sndr>, Tag>;
    +
    +
  8. +

    For a type T, SET-VALUE-SIG(T) denotes the type set_value_t() if T is cv void; otherwise, it denotes the type set_value_t(T).

    +
  9. +

    Library-provided sender types:

    +
      +
    • +

      Always expose an overload of a customization of connect that accepts an rvalue sender.

      +
    • +

      Only expose an overload of a customization of connect that + accepts an lvalue sender if they model copy_constructible.

      +
    • +

      Model copy_constructible if they satisfy copy_constructible.

      +
    +
+

11.9.3. Awaitable helpers [exec.awaitables]

+
    +
  1. +

    The sender concepts recognize awaitables as senders. For this clause +([exec]), an awaitable is an expression that would be +well-formed as the operand of a co_await expression within a given +context.

    +
  2. +

    For a subexpression c, let GET-AWAITER(c, p) be +expression-equivalent to the series of transformations and conversions +applied to c as the operand of an await-expression in a coroutine, +resulting in lvalue e as described by [expr.await]/3.2-4, where p is an lvalue referring to the coroutine’s promise type, Promise. This includes the invocation of the promise type’s await_transform member if any, the invocation of the operator co_await picked by overload resolution if any, and any necessary implicit +conversions and materializations.

    +
    I have opened cwg#250 to give these +transformations a term-of-art so we can more easily refer to it here.
    +
  3. +

    Let is-awaitable be the following exposition-only +concept:

    +
    template<class T>
    +concept await-suspend-result = see below;
    +
    +template<class A, class Promise>
    +concept is-awaiter = // exposition only
    +  requires (A& a, coroutine_handle<Promise> h) {
    +    a.await_ready() ? 1 : 0;
    +    { a.await_suspend(h) } -> await-suspend-result;
    +    a.await_resume();
    +  };
    +
    +template<class C, class Promise>
    +concept is-awaitable =
    +  requires (C (*fc)() noexcept, Promise& p) {
    +    { GET-AWAITER(fc(), p) } -> is-awaiter<Promise>;
    +  };
    +
    +

    await-suspend-result<T> is true if and only if one + of the following is true:

    +
      +
    • +

      T is void, or

      +
    • +

      T is bool, or

      +
    • +

      T is a specialization of coroutine_handle.

      +
    +
  4. +

    For a subexpression c such that decltype((c)) is type C, and +an lvalue p of type Promise, await-result-type<C, Promise> denotes the type decltype(GET-AWAITER(c, p).await_resume()).

    +
  5. +

    Let with-await-transform be the exposition-only class template:

    +
    template<class Derived>
    +struct with-await-transform {
    +  template<class T>
    +  T&& await_transform(T&& value) noexcept {
    +    return std::forward<T>(value);
    +  }
    +
    +  template<class T>
    +    requires tag_invocable<as_awaitable_t, T, Derived&>
    +  auto await_transform(T&& value)
    +    noexcept(nothrow_tag_invocable<as_awaitable_t, T, Derived&>)
    +    -> tag_invoke_result_t<as_awaitable_t, T, Derived&> {
    +    return tag_invoke(as_awaitable, std::forward<T>(value), static_cast<Derived&>(*this));
    +  }
    +};
    +
    +
  6. +

    Let env-promise be the exposition-only class template:

    +
    template<class Env>
    +struct env-promise : with-await-transform<env-promise<Env>> {
    +  unspecified get_return_object() noexcept;
    +  unspecified initial_suspend() noexcept;
    +  unspecified final_suspend() noexcept;
    +  void unhandled_exception() noexcept;
    +  void return_void() noexcept;
    +  coroutine_handle<> unhandled_stopped() noexcept;
    +
    +  friend const Env& tag_invoke(get_env_t, const env-promise&) noexcept;
    +};
    +
    +

    Specializations of env-promise are only used for the purpose of type computation; its members need not be + defined.

    +
+

11.9.4. execution::default_domain [exec.domain.default]

+
struct default_domain {
+  template <sender Sndr>
+    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr) noexcept(see below);
+
+  template <sender Sndr, queryable Env>
+    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env& env) noexcept(see below);
+
+  template <sender Sndr, queryable Env>
+    static constexpr decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+
+  template<class Tag, sender Sndr, class... Args>
+    static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+};
+
+
11.9.4.1. Static members [exec.domain.default.statics]
+
template <sender Sndr>
+  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr) noexcept(see below);
+
+
    +
  1. +

    Returns: tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr)) if that expression is well-formed; otherwise, std::forward<Sndr>(sndr).

    +
  2. +

    Remarks: The exception specification is equivalent to:

    +
    noexcept(tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr)))
    +
    +

    if that expression is well-formed; otherwise, true;

    +
+
template <sender Sndr, queryable Env>
+  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr, const Env& env) noexcept(see below);
+
+
    +
  1. +

    Returns: tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr), env) if that expression is well-formed; otherwise, std::forward<Sndr>(sndr).

    +
  2. +

    Remarks: The exception specification is equivalent to:

    +
    noexcept(tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr), env))
    +
    +

    if that expression is well-formed; otherwise, true;

    +
+
template <sender Sndr, queryable Env>
+  constexpr decltype(auto) default_domain::transform_env(Sndr&& sndr, Env&& env) noexcept;
+
+
    +
  1. +

    Returns: tag_of_t<Sndr>().transform_env(std::forward<Sndr>(sndr), std::forward<Env>(env)) if that expression is well-formed; otherwise, static_cast<Env>(std::forward<Env>(env)).

    +
  2. +

    Mandates: The selected expression in Returns: is not potentially throwing.

    +
+
template<class Tag, sender Sndr, class... Args>
+  static constexpr decltype(auto) default_domain::apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+
+
    +
  1. +

    Returns: Tag().apply_sender(std::forward<Sndr>(sndr), std::forward<Args>(args)...) if that expression is well-formed; otherwise, this function shall not participate +in overload resolution.

    +
  2. +

    Remarks: The exception specification is equivalent to:

    +
    noexcept(Tag().apply_sender(std::forward<Sndr>(sndr), std::forward<Args>(args)...))
    +
    +
+

11.9.5. execution::transform_sender [exec.snd.transform]

+
template<class Domain, sender Sndr>
+  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr);
+
+template<class Domain, sender Sndr, queryable Env>
+  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env& env);
+
+
    +
  1. +

    Returns: Let ENV be a parameter pack consisting of + the single expression env for the second overload and an empty pack for + the first. Let sndr2 be the expression dom.transform_sender(std::forward<Sndr>(sndr), ENV...) if that expression is well-formed; otherwise, default_domain().transform_sender(std::forward<Sndr>(sndr), ENV...). If sndr2 and sndr have the same type ignoring cv qualifiers, returns sndr2; otherwise, transform_sender(dom, sndr2, ENV...).

    +
+
template<class Domain, sender Sndr, queryable Env>
+  constexpr decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+
+
    +
  1. +

    Returns: dom.transform_sender(std::forward<Sndr>(sndr), std::forward<Env>(env)) if that + expression is well-formed; otherwise, default_domain().transform_sender(std::forward<Sndr>(sndr), std::forward<Env>(env)).

    +
+

11.9.6. execution::apply_sender [exec.snd.apply]

+
template<class Domain, class Tag, sender Sndr, class... Args>
+  constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+
+
    +
  1. +

    Returns: dom.apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...) if that + expression is well-formed; otherwise, default_domain().apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...) if that expression is well-formed; otherwise, this function shall not participate in + overload resolution.

    +
  2. +

    Remarks: The exception specification is equivalent to:

    +
    noexcept(dom.apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...))
    +
    +

    if that expression is well-formed; otherwise,

    +
    noexcept(default_domain().apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...))
    +
    +
+

11.9.7. execution::get_completion_signatures [exec.getcomplsigs]

+
    +
  1. +

    get_completion_signatures is a customization point object. Let sndr be an +expression such that decltype((sndr)) is Sndr, and let env be an expression +such that decltype((env)) is Env. Then get_completion_signatures(sndr, env) is +expression-equivalent to:

    +
      +
    1. +

      tag_invoke_result_t<get_completion_signatures_t, Sndr, Env>{} if that +expression is well-formed,

      +
    2. +

      Otherwise, remove_cvref_t<Sndr>::completion_signatures{} if that expression is well-formed,

      +
    3. +

      Otherwise, if is-awaitable<Sndr, env-promise<Env>> is true, then:

      +
      completion_signatures<
      +  SET-VALUE-SIG(await-result-type<Sndr, env-promise<Env>>), // see [exec.snd.concepts]
      +  set_error_t(exception_ptr),
      +  set_stopped_t()>{}
      +
      +
    4. +

      Otherwise, get_completion_signatures(sndr, env) is ill-formed.

      +
    +
  2. +

    Let rcvr be an rvalue receiver of type Rcvr, and let Sndr be the type of a +sender such that sender_in<Sndr, env_of_t<Rcvr>> is true. Let Sigs... be the +template arguments of the completion_signatures specialization named by completion_signatures_of_t<Sndr, env_of_t<Rcvr>>. Let CSO be +a completion function. If sender Sndr or its operation state cause the +expression CSO(rcvr, args...) to be potentially evaluated +([basic.def.odr]) then there shall be a signature Sig in Sigs... such +that MATCHING-SIG(tag_t<CSO>(decltype(args)...), Sig) is true ([exec.general]).

    +
+

11.9.8. execution::connect [exec.connect]

+
    +
  1. +

    connect connects ([async.ops]) a sender with a receiver.

    +
  2. +

    The name connect denotes a customization point object. For subexpressions sndr and rcvr, let Sndr be decltype((sndr)) and Rcvr be decltype((rcvr)), and let DS and DR be the decayed types of Sndr and Rcvr, respectively.

    +
  3. +

    Let connect-awaitable-promise be the following class:

    +
    struct connect-awaitable-promise : with-await-transform<connect-awaitable-promise> {
    +  DR& rcvr; // exposition only
    +
    +  connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
    +
    +  suspend_always initial_suspend() noexcept { return {}; }
    +  [[noreturn]] suspend_always final_suspend() noexcept { terminate(); }
    +  [[noreturn]] void unhandled_exception() noexcept { terminate(); }
    +  [[noreturn]] void return_void() noexcept { terminate(); }
    +
    +  coroutine_handle<> unhandled_stopped() noexcept {
    +    set_stopped((DR&&) rcvr);
    +    return noop_coroutine();
    +  }
    +
    +  operation-state-task get_return_object() noexcept {
    +    return operation-state-task{
    +      coroutine_handle<connect-awaitable-promise>::from_promise(*this)};
    +  }
    +
    +  friend env_of_t<const DR&> tag_invoke(get_env_t, const connect-awaitable-promise& self) noexcept {
    +    return get_env(self.rcvr);
    +  }
    +};
    +
    +
  4. +

    Let operation-state-task be the following class:

    +
    struct operation-state-task {
    +  using promise_type = connect-awaitable-promise;
    +  coroutine_handle<> coro; // exposition only
    +
    +  explicit operation-state-task(coroutine_handle<> h) noexcept : coro(h) {}
    +  operation-state-task(operation-state-task&& o) noexcept
    +    : coro(exchange(o.coro, {})) {}
    +  ~operation-state-task() { if (coro) coro.destroy(); }
    +
    +  friend void tag_invoke(start_t, operation-state-task& self) noexcept {
    +    self.coro.resume();
    +  }
    +};
    +
    +
  5. +

    Let V name the type await-result-type<DS, connect-awaitable-promise>, let Sigs name the type:

    +
    completion_signatures<
    +  SET-VALUE-SIG(V), // see [exec.snd.concepts]
    +  set_error_t(exception_ptr),
    +  set_stopped_t()>
    +
    +

    and let connect-awaitable be an exposition-only +coroutine defined as follows:

    +
    template<class Fun, class... Ts>
    +auto suspend-complete(Fun fun, Ts&&... as) noexcept { // exposition only
    +  auto fn = [&, fun]() noexcept { fun(std::forward<Ts>(as)...); };
    +
    +  struct awaiter {
    +    decltype(fn) fn_;
    +
    +    static bool await_ready() noexcept { return false; }
    +    void await_suspend(coroutine_handle<>) noexcept { fn_(); }
    +    [[noreturn]] void await_resume() noexcept { unreachable(); }
    +  };
    +  return awaiter{fn};
    +};
    +
    +operation-state-task connect-awaitable(DS sndr, DR rcvr) requires receiver_of<DR, Sigs> {
    +  exception_ptr ep;
    +  try {
    +    if constexpr (same_as<V, void>) {
    +      co_await std::move(sndr);
    +      co_await suspend-complete(set_value, std::move(rcvr));
    +    } else {
    +      co_await suspend-complete(set_value, std::move(rcvr), co_await std::move(sndr));
    +    }
    +  } catch(...) {
    +    ep = current_exception();
    +  }
    +  co_await suspend-complete(set_error, std::move(rcvr), std::move(ep));
    +}
    +
    +
  6. +

    If Sndr does not satisfy sender or if Rcvr does not satisfy receiver, connect(sndr, rcvr) is ill-formed. Otherwise, the expression connect(sndr, rcvr) is +expression-equivalent to:

    +
      +
    1. +

      tag_invoke(connect, sndr, rcvr) if connectable-with-tag-invoke<Sndr, Rcvr> is modeled.

      +
        +
      • +

        Mandates: The type of the tag_invoke expression above +satisfies operation_state.

        +
      +
    2. +

      Otherwise, connect-awaitable(sndr, rcvr) if that expression is +well-formed.

      +
    3. +

      Otherwise, connect(sndr, rcvr) is ill-formed.

      +
    +
+

11.9.9. Sender factories [exec.factories]

+
11.9.9.1. execution::schedule [exec.schedule]
+
    +
  1. +

    schedule obtains a schedule-sender ([async.ops]) from a scheduler.

    +
  2. +

    The name schedule denotes a customization point object. For some +subexpression sch, the expression schedule(sch) is expression-equivalent to:

    +
      +
    1. +

      tag_invoke(schedule, sch), if that expression is valid. If the function +selected by tag_invoke does not return a sender whose set_value completion scheduler is equivalent to sch, the behavior of calling schedule(sch) is undefined.

      +
        +
      • +

        Mandates: The type of the tag_invoke expression above +satisfies sender.

        +
      +
    2. +

      Otherwise, schedule(sch) is ill-formed.

      +
    +
+
11.9.9.2. execution::just, execution::just_error, execution::just_stopped [exec.just]
+
    +
  1. +

    just, just_error, and just_stopped are sender factories whose +asynchronous operations complete synchronously in their start operation +with a value completion operation, an error completion operation, or a +stopped completion operation respectively.

    +
  2. +

    The names just, just_error, and just_stopped denote customization +point objects. Let just-cpo be one of just, just_error, or just_stopped. For a pack of subexpressions ts, let Ts be the template parameter pack decltype((ts)). The expression just-cpo(ts...) is ill-formed if:

    +
      +
    • +

      (movable-value<Ts> &&...) is false, or

      +
    • +

      just-cpo is just_error and sizeof...(ts) == 1 is false, or

      +
    • +

      just-cpo is just_stopped and sizeof...(ts) == 0 is false;

      +
    +

    Otherwise, it is expression-equivalent to make-sender(just-cpo, product-type{vs...}).

    +
  3. +

    For just, just_error, and just_stopped, let set-cpo be set_value, set_error, and set_stopped respectively. The +exposition-only class template impls-for ([exec.snd.general]) is specialized for just-cpo as +follows:

    +
    template<>
    +struct impls-for<tag_t<just-cpo>> : default-impls {
    +  static constexpr auto start =
    +    [](auto& state, auto& rcvr) noexcept -> void {
    +      auto& [...ts] = state;
    +      set-cpo(std::move(rcvr), std::move(ts)...);
    +    };
    +};
    +
    +
+
11.9.9.3. execution::read [exec.read]
+
    +
  1. +

    read is a sender factory for a sender whose asynchronous operation +completes synchronously in its start operation with a value completion +result equal to a value read from the receiver’s associated environment.

    +
  2. +

    read is a customization point object. For some query object q, +the expression read(q) is expression-equivalent to make-sender(read, q).

    +
  3. +

    The exposition-only class template impls-for ([exec.snd.general]) +is specialized for read as follows:

    +
    template<>
    +struct impls-for<tag_t<read>> : default-impls {
    +  static constexpr auto start = [](auto query, auto& rcvr) noexcept -> void {
    +    TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
    +  };
    +};
    +
    +
+

11.9.10. Sender adaptors [exec.adapt]

+
11.9.10.1. General [exec.adapt.general]
+
    +
  1. +

    Subclause [exec.adapt] specifies a set of sender adaptors.

    +
  2. +

    The bitwise OR operator is overloaded for the purpose of creating sender +chains. The adaptors also support function call syntax with equivalent +semantics.

    +
  3. +

    Unless otherwise specified, a sender adaptor is required to not begin +executing any functions that would observe or modify any of the arguments +of the adaptor before the returned sender is connected with a receiver using connect, and start is called on the resulting operation state. This +requirement applies to any function that is selected by the implementation +of the sender adaptor.

    +
  4. +

    Unless otherwise specified, a parent sender ([async.ops]) with a single child +sender sndr has an associated attribute object equal to FWD-ENV(get_env(sndr)) ([exec.fwd.env]). Unless +otherwise specified, a parent sender with more than one child senders has an +associated attributes object equal to empty_env{}. These +requirements apply to any function that is selected by the implementation of +the sender adaptor.

    +
  5. +

    Unless otherwise specified, when a parent sender is connected to a receiver rcvr, any receiver used to connect a child sender has an associated +environment equal to FWD-ENV(get_env(rcvr)). This +requirements applies to any sender returned from a function that is selected +by the implementation of such sender adaptor.

    +
  6. +

    For any sender type, receiver type, operation state type, queryable type, or +coroutine promise type that is part of the implementation of any sender +adaptor in this subclause and that is a class template, the template +arguments do not contribute to the associated entities +([basic.lookup.argdep]) of a function call where a specialization of the +class template is an associated entity.

    +

    [Example:

    +
    namespace sender-adaptors { // exposition only
    +  template<class Sch, class Sndr> // arguments are not associated entities ([lib.tmpl-heads])
    +  class on-sender {
    +    // ...
    +  };
    +
    +  struct on_t {
    +    template<scheduler Sch, sender Sndr>
    +    on-sender<Sch, Sndr> operator()(Sch&& sch, Sndr&& sndr) const {
    +      // ...
    +    }
    +  };
    +}
    +inline constexpr sender-adaptors::on_t on{};
    +
    +

    -- end example]

    +
  7. +

    If a sender returned from a sender adaptor specified in this subclause is +specified to include set_error_t(Err) among its set of completion signatures +where decay_t<Err> denotes the type exception_ptr, but the implementation +does not potentially evaluate an error completion operation with an exception_ptr argument, the implementation is allowed to omit the exception_ptr error completion signature from the set.

    +
+
11.9.10.2. Sender adaptor closure objects [exec.adapt.objects]
+
    +
  1. +

    A pipeable sender adaptor closure object is a function object that +accepts one or more sender arguments and returns a sender. For a sender +adaptor closure object c and an expression sndr such that decltype((sndr)) models sender, the following expressions are equivalent +and yield a sender:

    +
    c(sndr)
    +sndr | c
    +
    +

    Given an additional pipeable sender adaptor closure object d, the expression c | d produces another pipeable sender adaptor closure object e:

    +

    e is a perfect forwarding call wrapper ([func.require]) with the following properties:

    +
      +
    • +

      Its target object is an object d2 of type decay_t<decltype((d))> direct-non-list-initialized with d.

      +
    • +

      It has one bound argument entity, an object c2 of type decay_t<decltype((c))> direct-non-list-initialized with C.

      +
    • +

      Its call pattern is d2(c2(arg)), where arg is the argument used in a function call expression of e.

      +
    +

    The expression c | d is well-formed if and only if the initializations of the state entities of e are all well-formed.

    +
  2. +

    An object t of type T is a pipeable sender adaptor closure object if T models derived_from<sender_adaptor_closure<T>>, T has no other base +classes of type sender_adaptor_closure<U> for any other type U, and T does not model sender.

    +
  3. +

    The template parameter D for sender_adaptor_closure can be an incomplete type. Before any expression of type cv D appears as +an operand to the | operator, D shall be complete and model derived_from<sender_adaptor_closure<D>>. The behavior of an expression involving an +object of type cv D as an operand to the | operator is undefined if overload resolution selects a program-defined operator| function.

    +
  4. +

    A pipeable sender adaptor object is a customization point object that accepts a sender as its first argument and returns a sender.

    +
  5. +

    If a pipeable sender adaptor object accepts only one argument, then it is a pipeable sender adaptor closure object.

    +
  6. +

    If a pipeable sender adaptor object adaptor accepts more than one argument, then let sndr be an expression such that decltype((sndr)) models sender, +let args... be arguments such that adaptor(sndr, args...) is a well-formed expression as specified in the rest of this subclause +([exec.adapt.objects]), and let BoundArgs be a pack that denotes decay_t<decltype((args))>.... The expression adaptor(args...) produces a pipeable sender adaptor closure object f that is a perfect forwarding call wrapper with the following properties:

    +
      +
    • +

      Its target object is a copy of adaptor.

      +
    • +

      Its bound argument entities bound_args consist of objects of types BoundArgs... direct-non-list-initialized with std::forward<decltype((args))>(args)..., respectively.

      +
    • +

      Its call pattern is adaptor(rcvr, bound_args...), where rcvr is the argument used in a function call expression of f.

      +
    +

    The expression adaptor(args...) is well-formed if and only if the initializations of the bound argument entities of the result, as specified above, + are all well-formed.

    +
+
11.9.10.3. execution::on [exec.on]
+
    +
  1. +

    on adapts an input sender into a sender that will start on an execution +agent belonging to a particular scheduler’s associated execution resource.

    +
  2. +

    The name on denotes a customization point object. For some subexpressions sch and sndr, if decltype((sch)) does not satisfy scheduler, or decltype((sndr)) does not satisfy sender, on(sch, sndr) is ill-formed.

    +
  3. +

    Otherwise, the expression on(sch, sndr) is expression-equivalent to:

    +
    transform_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  make-sender(on, sch, sndr));
    +
    +
  4. +

    Let out_sndr and env be subexpressions such that OutSndr is decltype((out_sndr)). If sender-for<OutSndr, on_t> is false, then the expressions on.transform_env(out_sndr, env) and on.transform_sender(out_sndr, env) are ill-formed; +otherwise:

    +
      +
    • +

      on.transform_env(out_sndr, env) is equivalent to:

      +
      auto&& [ign1, sch, ign2] = out_sndr;
      +return JOIN-ENV(SCHED-ENV(sch), FWD-ENV(env));
      +
      +
    • +

      on.transform_sender(out_sndr, env) is equivalent to:

      +
      auto&& [ign, sch, sndr] = out_sndr;
      +return let_value(
      +  schedule(sch),
      +  [sndr = std::forward_like<OutSndr>(sndr)]() mutable {
      +    return std::move(sndr);
      +  });
      +
      +
    +
  5. +

    Let out_sndr be a subexpression denoting a sender returned from on(sch, sndr) or one equal to such, and let OutSndr be the type decltype((out_sndr)). Let out_rcvr be a subexpression denoting a receiver that has an environment of +type Env such that sender_in<OutSndr, Env> is true. Let op be an lvalue +referring to the operation state that results from connecting out_sndr with out_rcvr. Calling start(op) shall start sndr on an execution agent of the +associated execution resource of sch, or failing that, shall execute an +error completion on out_rcvr.

    +
+
11.9.10.4. execution::transfer [exec.transfer]
+
    +
  1. +

    transfer adapts a sender into one with a different associated set_value completion scheduler. It results in a transition +between different execution resources when executed.

    +
  2. +

    The name transfer denotes a customization point object. For some +subexpressions sch and sndr, if decltype((sch)) does not satisfy scheduler, or decltype((sndr)) does not satisfy sender, transfer(sndr, sch) is ill-formed.

    +
  3. +

    Otherwise, the expression transfer(sndr, sch) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(transfer, sch, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for is specialized +for transfer_t as follows:

    +
    template<>
    +struct impls-for<transfer_t> : default-impls {
    +  static constexpr auto get_attrs =
    +    [](const auto& data, const auto& child) noexcept -> decltype(auto) {
    +      return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
    +    };
    +};
    +
    +
  5. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)). If sender-for<Sndr, transfer_t> is false, then the expression transfer.transform_sender(sndr, env) is ill-formed; otherwise, it +is equal to:

    +
    auto [tag, data, child] = sndr;
    +return schedule_from(std::move(data), std::move(child));
    +
    +

    This causes the transfer(sndr, sch) sender to become schedule_from(sch, sndr) when it is connected with a receiver with an +execution domain that does not customize transfer.

    +
  6. +

    Let out_sndr be a subexpression denoting a sender returned from transfer(sndr, sch) or one equal to such, and let OutSndr be the type decltype((out_sndr)). Let out_rcvr be a subexpression denoting a +receiver that has an environment of type Env such that sender_in<OutSndr, Env> is true. Let op be an lvalue referring to the operation state that +results from connecting out_sndr with out_rcvr. Calling start(op) shall start sndr on the current execution agent and execute completion +operations on out_rcvr on an execution agent of the execution resource +associated with sch. If scheduling onto sch fails, execute an error +completion on out_rcvr on an unspecified execution agent.

    +
+
11.9.10.5. execution::schedule_from [exec.schedule.from]
+
    +
  1. +

    schedule_from schedules work dependent on the completion of a sender onto a +scheduler’s associated execution resource. schedule_from is not meant to be used in user code; it is +used in the implementation of transfer.

    +
  2. +

    The name schedule_from denotes a customization point object. For some +subexpressions sch and sndr, let Sch be decltype((sch)) and Sndr be decltype((sndr)). If Sch does not satisfy scheduler, or Sndr does not +satisfy sender, schedule_from is ill-formed.

    +
  3. +

    Otherwise, the expression schedule_from(sch, sndr) is expression-equivalent +to:

    +
    transform_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  make-sender(schedule_from, sch, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for schedule_from_t as +follows:

    +
    template<>
    +struct impls-for<schedule_from_t> : default-impls {
    +  static constexpr auto get-attrs = see below;
    +  static constexpr auto get-state = see below;
    +  static constexpr auto complete = see below;
    +};
    +
    +
      +
    1. +

      The member impls-for<schedule_from_t>::get-attrs is initialized +with a callable object equivalent to the following lambda:

      +
      [](const auto& data, const auto& child) noexcept -> decltype(auto) {
      +  return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
      +}
      +
      +
    2. +

      The member impls-for<schedule_from_t>::get-state is initialized +with a callable object equivalent to the following lambda:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
      +    requires sender_in<child-type<Sndr>, env_of_t<Rcvr>> {
      +  return apply(
      +    [&]<class Sch, class Child>(auto, Sch sch, Child&& child) {
      +      using variant-type = see below;
      +      using receiver-type = see below;
      +      using operation-type = connect_result_t<schedule_result_t<Sch>, receiver-type>;
      +
      +      struct state-type {
      +        Rcvr& rcvr;
      +        variant-type async-result;
      +        operation-type op-state;
      +
      +        explicit state-type(Sch sch, Rcvr& rcvr)
      +          : rcvr(rcvr), op-state(connect(schedule(sch), receiver-type{{}, this})) {}
      +      };
      +
      +      return state-type{sch, rcvr};
      +    },
      +    std::forward<Sndr>(sndr));
      +}
      +
      +
        +
      1. +

        The local class state-type is a structural type.

        +
      2. +

        Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<Child, env_of_t<Rcvr>>. Let as-tuple be an alias template that transforms a + completion signature Tag(Args...) into the tuple specialization decayed-tuple<Tag, Args...>. + Then variant-type denotes the type variant<monostate, as-tuple<Sigs>...>, + except with duplicate types removed.

        +
      3. +

        Let receiver-type denote the following class:

        +
        struct receiver-type : receiver_adaptor<receiver-type> {
        +  state-type* state; // exposition only
        +
        +  Rcvr&& base() && noexcept { return std::move(state->rcvr); }
        +  const Rcvr& base() const & noexcept { return state->rcvr; }
        +
        +  void set_value() && noexcept {
        +    visit(
        +      [this]<class Tuple>(Tuple& result) noexcept -> void {
        +        if constexpr (!same_as<monostate, Tuple>) {
        +          auto& [tag, ...args] = result;
        +          tag(std::move(state->rcvr), std::move(args)...);
        +        }
        +      },
        +      state->async-result);
        +  }
        +};
        +
        +
      +
    3. +

      The member impls-for<schedule_from_t>::complete is initialized with a callable object equivalent to the following lambda:

      +
      []<class Tag, class... Args>(auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
      +  using result_t = decayed-tuple<Tag, Args...>;
      +  constexpr bool nothrow = is_nothrow_constructible_v<result_t, Tag, Args...>;
      +
      +  TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) {
      +    state.async-result.template emplace<result_t>(Tag(), std::forward<Args>(args)...);
      +  }());
      +
      +  if (state.async-result.valueless_by_exception())
      +    return;
      +  if (state.async-result.index() == 0)
      +    return;
      +
      +  start(state.op-state);
      +};
      +
      +
    +
  5. +

    Let the subexpression out_sndr denote the result of the invocation schedule_from(sch, sndr) or an object copied or moved from such, and let +the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an +asynchronous operation ([async.ops]) that, when started:

    +
      +
    • +

      eventually completes on an execution agent belonging to the associated +execution resource of sch, and

      +
    • +

      completes with the same async result as sndr.

      +
    +
+
11.9.10.6. execution::then, execution::upon_error, execution::upon_stopped [exec.then]
+
    +
  1. +

    then attaches an invocable as a continuation for an input sender’s value +completion operation. upon_error and upon_stopped do the same for the +error and stopped completion operations respectively, sending the result +of the invocable as a value completion.

    +
  2. +

    The names then, upon_error, and upon_stopped denote customization point +objects. Let the expression then-cpo be one of then, upon_error, or upon_stopped. For subexpressions sndr and f, let Sndr be decltype((sndr)) and let F be the decayed type of f. If Sndr does not +satisfy sender, or F does not satisfy movable-value, then-cpo(sndr, f) is ill-formed.

    +
  3. +

    Otherwise, the expression then-cpo(sndr, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(then-cpo, f, sndr));
    +
    +
  4. +

    For then, upon_error, and upon_stopped, let set-cpo be set_value, set_error, and set_stopped respectively. The +exposition-only class template impls-for ([exec.snd.general]) is specialized for then-cpo as follows:

    +
    template<>
    +struct impls-for<tag_t<then-cpo>> : default-impls {
    +  static constexpr auto complete =
    +    []<class Tag, class... Args>
    +      (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
    +        if constexpr (same_as<Tag, tag_t<set-cpo>>) {
    +          TRY-SET-VALUE(std::move(rcvr),
    +                        invoke(std::move(fn), std::forward<Args>(args)...));
    +        } else {
    +          Tag()(std::move(rcvr), std::forward<Args>(args)...);
    +        }
    +      };
    +};
    +
    +
  5. +

    The expression then-cpo(sndr, f) has undefined behavior +unless it returns a sender out_sndr that:

    +
      +
    1. +

      Invokes f or a copy of such with the value, error, or stopped result +datums of sndr (for then, upon_error, and upon_stopped respectively), using the result value of f as out_sndr's value +completion, and

      +
    2. +

      Forwards all other completion operations unchanged.

      +
    +
+
11.9.10.7. execution::let_value, execution::let_error, execution::let_stopped, [exec.let]
+
    +
  1. +

    let_value, let_error, and let_stopped transform a sender’s value, +error, and stopped completions respectively into a new child asynchronous +operation by passing the sender’s result datums to a user-specified +callable, which returns a new sender that is connected and started.

    +
  2. +

    Let the expression let-cpo be one of let_value, let_error, or let_stopped and let set-cpo be the +completion function that corresponds to let-cpo (set_value for let_value, etc.). For a subexpression sndr, let let-env(sndr) be expression-equivalent to the first +well-formed expression below:

    +
      +
    • +

      SCHED-ENV(get_completion_scheduler<tag_t<set-cpo>>(get_env(sndr)))

      +
    • +

      MAKE-ENV(get_domain, get_domain(get_env(sndr)))

      +
    • +

      empty_env{}

      +
    +
  3. +

    The names let_value, let_error, and let_stopped denote customization +point objects. For subexpressions sndr and f, let Sndr be decltype((sndr)), +let F be the decayed type of f. If Sndr does not satisfy sender or if F does not satisfy movable-value, the expression let-cpo(sndr, f) is ill-formed. If F does not satisfy invocable, the expression let_stopped(sndr, f) is ill-formed.

    +
  4. +

    Otherwise, the expression let-cpo(sndr, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(let-cpo, f, sndr));
    +
    +
  5. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for let-cpo as +follows:

    +
    template<class State, class Rcvr, class... Args>
    +void let-bind(State& state, Rcvr& rcvr, Args&&... args); // exposition only
    +
    +template<>
    +struct impls-for<tag_t<let-cpo>> : default-impls {
    +  static constexpr auto get-state = see below;
    +  static constexpr auto complete = see below;
    +};
    +
    +
      +
    1. +

      Let receiver2 denote the following exposition-only class template:

      +
      template<class Rcvr, class Env>
      +struct receiver2 : receiver_adaptor<receiver2<Rcvr, Env>, Rcvr> {
      +  explicit receiver2(Rcvr rcvr, Env env)
      +    : receiver2::receiver_adaptor{std::move(rcvr)}, env(std::move(env)) {}
      +
      +  auto get_env() const noexcept {
      +    return JOIN-ENV(env, FWD-ENV(execution::get_env(this->base())));
      +  }
      +
      +  Env env; // exposition only
      +};
      +
      +
    2. +

      impls-for<tag_t<let-cpo>>::get-state is +is initialized with a callable object equivalent to the following:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) requires see below {
      +  auto&& [tag, data, child] = std::forward<Sndr>(sndr);
      +  return [&]<class Fn, class Env>(Fn fn, Env env) {
      +    using args-variant-type = see below;
      +    using ops2-variant-type = see below;
      +
      +    struct state-type {
      +      Fn fn;
      +      Env env;
      +      args-variant-type args;
      +      ops2-variant-type ops2;
      +    };
      +    return state-type{std::move(fn), std::move(env), {}, {}};
      +  }(std::forward_like<Sndr>(data), let-env(child));
      +}
      +
      +
        +
      1. +

        Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<child-type<Sndr>, env_of_t<Rcvr>>. Let LetSigs be a pack of those types in Sigs with a return type of tag_t<set-cpo>. Let as-tuple be an alias template such that as-tuple<Tag(Args...)> denotes the type decayed-tuple<Args...>. Then args-variant-type denotes the type variant<monostate, as-tuple<LetSigs>...>.

        +
      2. +

        Let as-sndr2 be an alias template such that as-sndr2<Tag(Args...)> denotes the type call-result-t<Fn, decay_t<Args>&...>. +Then ops2-variant-type denotes the type variant<monostate, connect_result_t<as-sndr2<LetSigs>, receiver2<Rcvr, Env>>...>.

        +
      3. +

        The requires-clause constraining the above lambda is +satisfied if and only if the types args-variant-type and ops2-variant-type are well-formed.

        +
      +
    3. +

      The exposition-only function template let-bind is equal to:

      +
      auto& args = state.args.emplace<decayed-tuple<Args...>>(std::forward<Args>(args)...);
      +auto sndr2 = apply(std::move(state.fn), args);
      +auto rcvr2 = receiver2{std::move(rcvr), std::move(state.env)};
      +auto mkop2 = [&] { return connect(std::move(sndr2), std::move(rcvr2)); };
      +auto& op2 = state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2});
      +start(op2);
      +
      +
    4. +

      impls-for<tag_t<let-cpo>>::complete is +is initialized with a callable object equivalent to the following:

      +
      []<class Tag, class... Args>
      +  (auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
      +    if constexpr (same_as<Tag, tag_t<set-cpo>>) {
      +      TRY-EVAL(std::move(rcvr), let-bind(state, rcvr, std::forward<Args>(args)...));
      +    } else {
      +      Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +    }
      +  }
      +
      +
    +
  6. +

    Let sndr and env be subexpressions, and let Sndr be decltype((sndr)). +If sender-for<Sndr, tag_t<let-cpo>> is false, then the expression let-cpo.transform_env(sndr, env) is ill-formed. Otherwise, it is equal to JOIN-ENV(let-env(sndr), FWD-ENV(env)).

    +
  7. +

    Let the subexpression out_sndr denote the result of the invocation let-cpo(sndr, f) or an object copied or moved from such, +and let the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an asynchronous operation +([async.ops]) that, when started:

    +
      +
    • +

      invokes f when set-cpo is called with sndr's + result datums,

      +
    • +

      makes its completion dependent on the completion of a sender returned + by f, and

      +
    • +

      propagates the other completion operations sent by sndr.

      +
    +
+
11.9.10.8. execution::bulk [exec.bulk]
+
    +
  1. +

    bulk runs a task repeatedly for every index in an index space.

    +
  2. +

    The name bulk denotes a customization point object. For subexpressions sndr, shape, and f, let Sndr be decltype((sndr)), let Shape be +the decayed type of shape, and let F be the decayed type of f. If Sndr does not satisfy sender, or if Shape does not satisfy integral, +or if F does not satisfy movable-value, bulk(sndr, shape, f) is ill-formed.

    +
  3. +

    Otherwise, the expression bulk(sndr, shape, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(bulk, product-type{shape, f}, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for bulk_t as follows:

    +
    template<>
    +struct impls-for<bulk_t> : default-impls {
    +  static constexpr auto complete = see below;
    +};
    +
    +
      +
    1. +

      The member impls-for<bulk_t>::complete is +initialized with a callable object equivalent to the following lambda:

      +
      []<class Index, class State, class Rcvr, class Tag, class... Args>
      +  (Index, State& state, Rcvr& rcvr, Tag, Args&&... args) noexcept -> void requires see below {
      +    if constexpr (same_as<Tag, set_value_t>) {
      +      auto& [shape, f] = state;
      +      constexpr bool nothrow = noexcept(f(auto(shape), args...));
      +      TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) {
      +        for (auto max = shape, i = 0; i < max; ++i) {
      +          f(auto(i), args...);
      +        }
      +        Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +      }());
      +    } else {
      +      Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +    }
      +  }
      +
      +
        +
      1. +

        The expression in the requires-clause of the lambda above is true if and only if Tag denotes a type other than set_value_t or if the expression f(auto(shape), args...) is well-formed.

        +
      +
    +
  5. +

    Let the subexpression out_sndr denote the result of the invocation bulk(sndr, shape, f) or an object copied or moved from such, +and let the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an asynchronous operation +([async.ops]) that, when started:

    +
      +
    • +

      on a value completion operation, invokes f(i, args...) for every i of type Shape from 0 to shape, where args is a pack of lvalue + subexpressions referring to the value completion result datums of the + input sender, and

      +
    • +

      propagates all completion operations sent by sndr.

      +
    +
+
11.9.10.9. execution::split and execution::ensure_started [exec.split]
+
    +
  1. +

    split adapts an arbitrary sender into a sender that can be connected +multiple times. ensure_started eagerly starts the execution of a sender, +returning a sender that is usable as input to additional sender algorithms.

    +
  2. +

    Let shared-env be the type of an environment such that, +given an instance env, the expression get_stop_token(env) is well-formed +and has type in_place_stop_token.

    +
  3. +

    + The names split and ensure_started denote customization point objects. +Let the expression shared-cpo be one of split or ensure_started. For a subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, shared-env> + or constructible_from<decay_t<env_of_t<Sndr>>, env_of_t<Sndr>> + is false, shared-cpo(sndr) is ill-formed. +

    +
    Although it has not yet been approved by LEWG, there +is a bug in the current wording that makes it impossible to safely copy the +attributes of a sender; it may have reference semantics, leading to a +dangling reference. I am striking this part for now and will bring a fix to +LEWG.
    +
  4. +

    Otherwise, the expression shared-cpo(sndr) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(shared-cpo, {}, sndr));
    +
    +
      +
    • +

      The default implementation of transform_sender will have the effect of connecting the sender to a receiver and, in the +case of ensure_started, calling start on the resulting operation +state. It will return a sender with a different tag type.

      +
    +
  5. +

    Let local-state denote the following exposition-only class:

    +
    struct local-state-base {
    +  virtual ~local-state-base() = default;
    +  virtual void notify() noexcept = 0;
    +  virtual void detach() noexcept = 0;
    +};
    +
    +template<class Sndr, class Rcvr>
    +struct local-state : local-state-base {
    +  using on-stop-request = see below;
    +  using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>::
    +                              template callback_type<on-stop-request>;
    +
    +  local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
    +  ~local-state();
    +
    +  void notify() noexcept override;
    +  void detach() noexcept override;
    +
    +  optional<on-stop-callback> on_stop;
    +  shared-state<Sndr>* sh_state;
    +  Rcvr* rcvr;
    +};
    +
    +
      +
    1. +
      local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
      +
        +
      1. +

        Effects: Equivalent to:

        +
        auto&& [tag, data, child] = std::forward<Sndr>(sndr);
        +this->sh_state = data.sh_state.get();
        +this->sh_state->inc-ref();
        +this->rcvr = &rcvr;
        +
        +
      +
    2. +
      ~local-state();
      +
        +
      1. +

        Effects: Equivalent to:

        +
        detach();
        +sh_state->dec-ref();
        +
        +
      +
    3. +
      void notify() noexcept override;
      +
        +
      1. +

        Effects: Equivalent to:

        +
        on_stop.reset();
        +visit(
        +  [this]<class Tuple>(Tuple&& tupl) noexcept -> void {
        +    apply(
        +      [this](auto tag, auto&... args) noexcept -> void {
        +        tag(std::move(*rcvr), std::forward_like<Tuple>(args)...);
        +      },
        +      tupl);
        +  },
        +  QUAL(sh_state->result));
        +);
        +
        +

        where QUAL is std::move if same_as<tag_of_t<Sndr>, ensure-started-impl-tag> is true, and as_const otherwise.

        +
      +
    4. +
      void detach() noexcept override;
      +
        +
      1. +

        Effects: Equivalent to sh_state->detach() if same_as<tag_of_t<Sndr>, ensure-started-impl-tag> is true; otherwise, +nothing.

        +
      +
    +
  6. +

    Let shared-receiver denote the following exposition-only class +template:

    +
    template<class Sndr>
    +struct shared-receiver {
    +  using receiver_concept = receiver_t;
    +
    +  template<completion-tag Tag, class... Args>
    +  friend void tag_invoke(Tag, shared-receiver&& self, Args&&... args) noexcept {
    +    try {
    +      using tuple_t = decayed-tuple<Tag, Args...>;
    +      self.sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
    +    } catch (...) {
    +      using tuple_t = tuple<set_error_t, exception_ptr>;
    +      self.sh_state->result.template emplace<tuple_t>(set_error, current_exception());
    +    }
    +    self.sh_state->notify();
    +  }
    +
    +  friend decltype(auto) tag_invoke(get_env_t, const shared-receiver& self) noexcept {
    +    return MAKE-ENV(get_stop_token, self.sh_state->stop_src.get_token());
    +  }
    +
    +  shared-state<Sndr>* sh_state;
    +};
    +
    +
  7. +

    Let shared-state denote the following exposition-only class +template:

    +
    template<class Sndr>
    +struct shared-state {
    +  using variant-type = see below;
    +  using state-list-type = see below;
    +  using state-flag-type = see below;
    +
    +  explicit shared-state(Sndr&& sndr);
    +
    +  void start-op() noexcept;
    +  void notify() noexcept;
    +  void detach() noexcept;
    +  void inc-ref() noexcept;
    +  void dec-ref() noexcept;
    +
    +  in_place_stop_source stop_src{};
    +  variant-type result{};
    +  state-list-type waiting_states;
    +  state-flag-type completed;
    +  atomic<size_t> ref_count{1};
    +  connect_result_t<Sndr, shared-receiver<Sndr>> op_state;
    +};
    +
    +
      +
    1. +

      Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<Sndr>. Let as-tuple be an + alias template such that as-tuple<Tag(Args...)> denotes the type decayed-tuple<Tag, Args...>. Then variant-type denotes the type variant<tuple<set_stopped_t>, tuple<set_error_t, exception_ptr>, as-tuple<Sigs>...>, but with + duplicate types removed.

      +
    2. +

      Let state-list-type be a type that stores a list of pointers + to local-state-base objects and that permits atomic insertion. + Let state-flag-type be a type that can be atomically toggled + between true and false.

      +
    3. +
        explicit shared-state(Sndr&& sndr);
      +
        +
      1. +

        Effects: Initializes op_state with the result of connect(std::forward<Sndr>(sndr), shared-receiver{this}).

        +
      2. +

        Postcondition: waiting_states is empty, and completed is false.

        +
      +
    4. +
        void start-op() noexcept;
      +
        +
      1. +

        Effects: inc-ref(). If stop_src.stop_requested() is true, calls notify(); otherwise, calls start(op_state).

        +
      +
    5. +
        void notify() noexcept;
      +
        +
      1. +

        Effects: Atomically does the following:

        +
          +
        • +

          Sets completed to true, and

          +
        • +

          Exchanges waiting_states with an empty list, storing the old +value in a local prior_states. For each pointer p in prior_states, calls p->notify(). +Finally, calls dec-ref().

          +
        +
      +
    6. +
        void detach() noexcept;
      +
        +
      1. +

        Effects: If completed is false and waiting_states is empty, + calls stop_src.request_stop(). This has + the effect of requesting early termination of any asynchronous + operation that was started as a result of a call to ensure_started, + but only if the resulting sender was never connected and started.

        +
      +
    7. +
        void inc-ref() noexcept;
      +
        +
      1. +

        Effects: Increments ref_count.

        +
      +
    8. +
        void dec-ref() noexcept;
      +
        +
      1. +

        Effects: Decrements ref_count. If the new value of ref_count is 0, calls delete this.

        +
      2. +

        Synchronization: If dec_ref() does not decrement the ref_count to 0 then synchronizes with + the call to dec_ref() that decrements ref_count to 0.

        +
      +
    +
  8. +

    For each type split_t and ensure_started_t, there is a different, +associated exposition-only implementation tag type, split-impl-tag and ensure-started-impl-tag, respectively. Let shared-impl-tag be the associated implementation tag type of shared-cpo. Given an expression sndr, the expression shared-cpo.transform_sender(sndr) is equivalent to:

    +
    auto&& [tag, data, child] = sndr;
    +auto* sh_state = new shared-state{std::forward_like<decltype((sndr))>(child)};
    +return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
    +
    +

    where shared-wrapper is an exposition-only class that manages the +reference count of the shared-state object pointed to by sh_state. shared-wrapper models movable with move operations nulling out the +moved-from object. If tag is split_t, shared-wrapper models copyable with copy operations incrementing the reference count by calling sh_state->inc-ref(). The constructor calls sh_state->start-op() if tag is ensure_started_t. The +destructor has no effect if sh_state is null; otherwise, it calls sh_state->detach() if tag is ensure_started_t; +and finally, it decrements the reference count by calling sh_state->dec-ref().

    +
  9. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for shared-impl-tag as follows:

    +
    template<>
    +struct impls-for<shared-impl-tag> : default-impls {
    +  static constexpr auto get-state = see below;
    +  static constexpr auto start = see below;
    +};
    +
    +
      +
    1. +

      The member impls-for<shared-impl-tag>::get-state is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class Sndr>(Sndr&& sndr, auto& rcvr) noexcept {
      +  return local-state{std::forward<Sndr>(sndr), rcvr};
      +}
      +
      +
    2. +

      The member impls-for<shared-impl-tag>::start is initialized with a callable object that has a call operator +equivalent to the following:

      +
      template <class Sndr, class Rcvr>
      +void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
      +
        +
      1. +

        Effects:

        +
          +
        1. +

          If state.sh_state->completed is true, calls state.notify() and returns.

          +
        2. +

          Otherwise, calls:

          +
          state.on_stop.emplace(
          +  get_stop_token(get_env(rcvr)),
          +  on-stop-request{state.sh_state->stop_src})
          +
          +

          If shared-impl-tag is ensure-started-impl-tag, and if state.sh_state->stop_src.stop_requested() is true, calls set_stopped(std::move(rcvr)) and returns.

          +
        3. +

          Then atomically does the following:

          +
            +
          • +

            Inserts &state into state.sh_state->waiting_states, and

            +
          • +

            Reads the value of state.sh_state->completed.

            +
          +

          If the value is true, calls state.notify() and returns.

          +
        4. +

          If shared-impl-tag is split-impl-tag, and if &state is the first item added to state.sh_state->waiting_states, calls state.sh_state->start-op().

          +
        +
      +
    +
  10. +
    + Under the following conditions, the results of the +child operation are discarded: +
      +
    • +

      When a sender returned from ensure_started is destroyed without being +connected to a receiver, or

      +
    • +

      If the sender is connected to a receiver but the operation state +is destroyed without having been started, or

      +
    • +

      If polling the receiver’s stop token indicates that stop has been +requested when start is called, and the operation has not yet +completed.

      +
    +
    +

    +
+
11.9.10.10. execution::when_all [exec.when.all]
+
    +
  1. +

    when_all and when_all_with_variant both adapt multiple input senders into +a sender that completes when all input senders have completed. when_all only accepts senders with a single value completion signature and on success +concatenates all the input senders' value result datums into its own value +completion operation. when_all_with_variant(sndrs...) is semantically +equivalent to when_all(into_variant(sndrs)...), where sndrs is a pack of +subexpressions of sender types.

    +
  2. +

    The names when_all and when_all_with_variant denote customization point +objects. For some subexpressions sndri..., let Sndri... be decltype((sndri)).... The expressions when_all(sndri...) and when_all_with_variant(sndri...) are ill-formed if +any of the following is true:

    +
      +
    • +

      If the number of subexpressions in sndri... is 0, or

      +
    • +

      If any type Sndri does not satisfy sender.

      +
    • +

      If the types of the expressions get-domain-early(sndri) do not share +a common type ([meta.trans.other]) for all values of i.

      +
    +

    Otherwise, let CD be the common type of the input senders' domains.

    +
  3. +

    The expression when_all(sndri...) is +expression-equivalent to:

    +
    transform_sender(
    +  CD(),
    +  make-sender(when_all, {}, sndr0, ... sndrn-1));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for when_all_t as follows:

    +
    template<>
    +struct impls-for<when_all_t> : default-impls {
    +  static constexpr auto get-attrs = see below;
    +  static constexpr auto get-env = see below;
    +  static constexpr auto get-state = see below;
    +  static constexpr auto start = see below;
    +  static constexpr auto complete = see below;
    +};
    +
    +
      +
    1. +

      The member impls-for<when_all_t>::get-attrs is initialized with a callable object equivalent to the following lambda +expression:

      +
      [](auto&&, auto&&... child) noexcept {
      +  auto domain_fn = []<class... Ds>(Ds...) noexcept { return common_type_t<Ds...>(); };
      +  using domain_type = decltype(domain_fn(get-domain-early(child)...));
      +  if constexpr (same_as<domain_type, default_domain>) {
      +    return empty_env();
      +  } else {
      +    return MAKE-ENV(get_domain, domain_type());
      +  }
      +}
      +
      +
    2. +

      The member impls-for<when_all_t>::get-env is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class State, class Rcvr>(auto&&, State& state, const Receiver& rcvr) noexcept {
      +  return JOIN-ENV(
      +    MAKE-ENV(get_stop_token, state.stop_src.get_token()), get_env(rcvr));
      +}
      +
      +
    3. +

      The member impls-for<when_all_t>::get-state is initialized with a callable object equivalent to the following lambda +expression:

      +
      BUG: apply isn’t constrained
      +[]<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) + -> decltype(apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr))) { + return apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr)); +} +
      +

      where make-state is the following exposition-only class type:

      +
      template<class Sndr, class Env>
      +concept max-1-sender-in = sender_in<Sndr, Env> &&
      +  (tuple_size_v<value_types_of_t<Sndr, Env, tuple, tuple>> <= 1);
      +
      +enum class disposition { started, error, stopped };
      +
      +template <class Rcvr>
      +struct make-state {
      +  const env_of_t<Rcvr>& env;
      +
      +  template <max-1-sender-in<env_of_t<Rcvr>>... Sndrs>
      +  auto operator()(auto, auto, Sndrs&&... sndrs) const {
      +    using values_tuple = see below;
      +    using errors_variant = see below;
      +    using stop_token = stop_token_of_t<env_of_t<Rcvr>>;
      +    using stop_callback = stop_token::template callback_type<on-stop-request>;
      +
      +    struct state {
      +      void arrive(Rcvr& rcvr) noexcept {
      +        if (0 == --count) {
      +          complete(rcvr);
      +        }
      +      }
      +
      +      void complete(Rcvr& rcvr) noexcept; // see below
      +
      +      atomic<size_t> count{sizeof...(sndrs)};
      +      in_place_stop_source stop_src{};
      +      atomic<disposition> disp{disposition::started};
      +      errors_variant errors{};
      +      values_tuple values{};
      +      optional<stop_callback> on_stop{nullopt};
      +    };
      +
      +    return state{};
      +  }
      +};
      +
      +
        +
      1. +

        Let copy-fail be exception_ptr if decay-copying any of the + input senders' result datums can potentially throw; otherwise, none-such, where none-such is an unspecified + empty class type.

        +
      2. +

        The alias values_tuple denotes the type tuple<value_types_of_t<Sndrs, env_of_t<Rcvr>, decayed-tuple, optional>...> if that type is well-formed; + otherwise, tuple<>.

        +
      3. +

        The alias errors_variant denotes the type variant<none-such, copy-fail, Es...> with duplicate types removed, where Es is the pack of the decayed types of all the + input senders' possible error result datums.

        +
      4. +

        The member void state::complete(Rcvr& rcvr) noexcept behaves as follows:

        +
          +
        1. +

          If disp is equal to disposition::started, + evaluates:

          +
          auto tie = []<class... T>(tuple<T...>& t) noexcept { return tuple<T&...>(t); };
          +auto set = [&](auto&... t) noexcept { set_value(std::move(rcvr), std::move(t)...); };
          +
          +on_stop.reset();
          +apply(
          +  [&](auto&... opts) noexcept {
          +    apply(set, tuple_cat(tie(*opts)...));
          +  },
          +  values);
          +
          +
        2. +

          Otherwise, if disp is equal to disposition::error, evaluates:

          +
          on_stop.reset();
          +visit(
          +  [&]<class Error>(Error& error) noexcept {
          +    if constexpr (!same_as<Error, none-such>) {
          +      set_error(std::move(rcvr), std::move(error));
          +    }
          +  },
          +  errors);
          +
          +
        3. +

          Otherwise, evaluates:

          +
          on_stop.reset();
          +set_stopped(std::move(rcvr));
          +
          +
        +
      +
    4. +

      The member impls-for<when_all_t>::start is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class State, class Rcvr, class... Ops>(
      +    State& state, Rcvr& rcvr, Ops&... ops) noexcept -> void {
      +  state.on_stop.emplace(
      +    get_stop_token(get_env(rcvr)),
      +    on-stop-request{state.stop_src});
      +  if (state.stop_src.stop_requested()) {
      +    state.on_stop.reset();
      +    set_stopped(std::move(rcvr));
      +  } else {
      +    (start(ops), ...);
      +  }
      +}
      +
      +
    5. +

      The member impls-for<when_all_t>::complete is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class Index, class State, class Rcvr, class Set, class... Args>(
      +    this auto& complete, Index, State& state, Rcvr& rcvr, Set, Args&&... args) noexcept -> void {
      +  if constexpr (same_as<Set, set_error_t>) {
      +    if (disposition::error != state.disp.exchange(disposition::error)) {
      +      state.stop_src.request_stop();
      +      TRY-EMPLACE-ERROR(state.errors, std::forward<Args>(args)...);
      +    }
      +  } else if constexpr (same_as<Set, set_stopped_t>) {
      +    auto expected = disposition::started;
      +    if (state.disp.compare_exchange_strong(expected, disposition::stopped)) {
      +      state.stop_src.request_stop();
      +    }
      +  } else if constexpr (!same_as<decltype(State::values), tuple<>>) {
      +    if (state.disp == disposition::started) {
      +      auto& opt = get<Index::value>(state.values);
      +      TRY-EMPLACE-VALUE(complete, opt, std::forward<Args>(args)...);
      +    }
      +  }
      +
      +  state.arrive(rcvr);
      +}
      +
      +

      where TRY-EMPLACE-ERROR(v, e), for subexpressions v and e, is equivalent to:

      +
      try {
      +  v.template emplace<decltype(auto(e))>(e);
      +} catch (...) {
      +  v.template emplace<exception_ptr>(current_exception());
      +}
      +
      +

      if the expression decltype(auto(e))(e) is potentially throwing; otherwise, v.template emplace<decltype(auto(e))>(e); and where TRY-EMPLACE-VALUE(c, o, as...), for subexpressions c, o, and pack of subexpressions as, is equivalent to:

      +
      try {
      +  o.emplace(as...);
      +} catch (...) {
      +  c(Index(), state, rcvr, set_error, current_exception());
      +  return;
      +}
      +
      +

      if the expression decayed-tuple<decltype(as)...>{as...} is potentially throwing; otherwise, o.emplace(as...).

      +
    +
  5. +

    The expression when_all_with_variant(sndri...) is +expression-equivalent to:

    +
    transform_sender(
    +  CD(),
    +  make-sender(when_all_with_variant, {}, sndr0, ... sndrn-1));
    +
    +
  6. +

    Given subexpressions sndr and env, if sender-for<decltype((sndr)), when_all_with_variant_t> is false, +then the expression when_all_with_variant.transform_sender(sndr, env) is +ill-formed; otherwise, the body of the transform_sender member-function is equivalent to:

    +
    auto [tag, data, ...child] = sndr;
    +return when_all(into_variant(std::move(child))...);
    +
    +

    This causes the when_all_with_variant(sndr...) sender +to become when_all(into_variant(sndr)...) when it is connected with a +receiver with an execution domain that does not customize when_all_with_variant.

    +
+
11.9.10.11. execution::into_variant [exec.into.variant]
+
    +
  1. +

    into_variant adapts a sender with multiple value completion signatures into +a sender with just one consisting of a variant of tuples.

    +
  2. +

    The template into-variant-type computes the type sent by +a sender returned from into_variant.

    +
    template<class Sndr, class Env>
    +    requires sender_in<Sndr, Env>
    +  using into-variant-type =
    +    value_types_of_t<Sndr, Env>;
    +
    +
  3. +

    The name into_variant denotes a customization point object. For a +subexpression sndr, let Sndr be decltype((sndr)). If Sndr does not +satisfy sender, into_variant(sndr) is ill-formed.

    +
  4. +

    Otherwise, the expression into_variant(sndr) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(into_variant, {}, sndr))
    +
    +
  5. +

    The exposition-only class template impls-for ([exec.snd.general]) is +specialized for into_variant as follows:

    +
    template<>
    +struct impls-for<into_variant_t> : default-impls {
    +  static constexpr auto get-state = see below;
    +  static constexpr auto complete = see below;
    +};
    +
    +
      +
    1. +

      The member impls-for<into_variant_t>::get-state is +initialized with a callable object equivalent to the following lambda:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept
      +  -> type_identity<into-variant-type<child-type<Sndr>, env_of_t<Rcvr>>> {
      +  return {};
      +}
      +
      +
    2. +

      The member impls-for<into_variant_t>::complete is initialized with a callable object equivalent to the following lambda:

      +
      []<class State, class Rcvr, class Tag, class... Args>(
      +    auto, State, Rcvr& rcvr, Tag, Args&&... args) noexcept {
      +  if constexpr (same_as<Tag, set_value_t>) {
      +    using variant_type = typename State::type;
      +    using tuple_type = decayed-tuple<Args...>;
      +    try {
      +      set_value(std::move(rcvr),
      +                variant_type(tuple_type(std::forward<Args>(args)...)));
      +    }
      +    catch (...) {
      +      set_error(std::move(rcvr), current_exception());
      +    }
      +  } else {
      +    Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +  }
      +}
      +
      +
    +
+
11.9.10.12. execution::stopped_as_optional [exec.stopped.as.optional]
+
    +
  1. +

    stopped_as_optional maps an input sender’s stopped completion operation into the value completion operation as an empty optional. The input sender’s value completion operation is also converted into an optional. The result is a sender that never completes with stopped, reporting cancellation by completing with an empty optional.

    +
  2. +

    The name stopped_as_optional denotes a customization point object. For some subexpression sndr, let Sndr be decltype((sndr)). +The expression stopped_as_optional(sndr) is expression-equivalent to:

    +
    transform_sender(
    +  get-sender-domain(sndr),
    +  make-sender(stopped_as_optional, {}, sndr))
    +
    +
  3. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)) and Env is decltype((env)). +If either sender-for<Sndr, stopped_as_optional_t> or single-sender<Sndr, Env> is false then the expression stopped_as_optional.transform_sender(sndr, env) is ill-formed; otherwise, it is equal to:

    +
    auto [tag, data, child] = sndr;
    +using V = single-sender-value-type<Sndr, Env>;
    +return let_stopped(
    +    then(std::move(child),
    +              []<class T>(T&& t) { return optional(std::forward(t)); }),
    +    []() noexcept { return just(optional()); });
    +
    +
+
11.9.10.13. execution::stopped_as_error [exec.stopped.as.error]
+
    +
  1. +

    stopped_as_error maps an input sender’s stopped completion operation into +an error completion operation as a custom error type. The result is a sender +that never completes with stopped, reporting cancellation by completing with +an error.

    +
  2. +

    The name stopped_as_error denotes a customization point object. For some subexpressions sndr and err, let Sndr be decltype((sndr)) and let Err be decltype((err)). If the type Sndr does not satisfy sender or if the type Err doesn’t satisfy movable-value, stopped_as_error(sndr, err) is ill-formed. Otherwise, the expression stopped_as_error(sndr, err) is expression-equivalent to:

    +
    transform_sender(
    +  get-sender-domain(sndr),
    +  make-sender(stopped_as_error, err, sndr))
    +
    +
  3. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)) and Env is decltype((env)). +If sender-for<Sndr, stopped_as_error_t> is false, then the expression stopped_as_error.transform_sender(sndr, env) is ill-formed; otherwise, it is equal to:

    +
    auto [tag, data, child] = sndr;
    +return let_stopped(
    +    std::move(child),
    +    [err = std::move(data)]() mutable { return just_error(std::move(err)); });
    +
    +
+

11.9.11. Sender consumers [exec.consumers]

+
11.9.11.1. execution::start_detached [exec.start.detached]
+
    +
  1. +

    start_detached eagerly starts a sender without the caller needing to manage +the lifetimes of any objects.

    +
  2. +

    The name start_detached denotes a customization point object. For some +subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, empty_env> is false, start_detached is ill-formed. +Otherwise, the expression start_detached(sndr) is expression-equivalent to:

    +
    apply_sender(get-sender-domain(sndr), start_detached, sndr)
    +
    +
      +
    • +

      Mandates: The type of the expression above is void.

      +
    +

    If the expression above does not eagerly start the sender sndr after +connecting it with a receiver that ignores value and stopped completion +operations and calls terminate() on error completions, the behavior of +calling start_detached(sndr) is undefined.

    +
  3. +

    Let sndr be a subexpression such that Sndr is decltype((sndr)), and let detached-receiver and detached-operation be the following exposition-only +class types:

    +
    struct detached-receiver {
    +  using receiver_concept = receiver_t;
    +  detached-operation* op; // exposition only
    +
    +  friend void tag_invoke(set_value_t, detached-receiver&& self) noexcept { delete self.op; }
    +  friend void tag_invoke(set_error_t, detached-receiver&&, auto&&) noexcept { terminate(); }
    +  friend void tag_invoke(set_stopped_t, detached-receiver&& self) noexcept { delete self.op; }
    +  friend empty_env tag_invoke(get_env_t, const detached-receiver&) { return {}; }
    +};
    +
    +struct detached-operation {
    +  connect_result_t<Sndr, detached-receiver> op; // exposition only
    +
    +  explicit detached-operation(Sndr&& sndr)
    +    : op(connect(std::forward<Sndr>(sndr), detached-receiver{this}))
    +  {}
    +};
    +
    +
  4. +

    If sender_to<Sndr, detached-receiver> is false, the +expression start_detached.apply_sender(sndr) is ill-formed; otherwise, it is +expression-equivalent to start(*new detached-operation(sndr)).

    +
+
11.9.11.2. this_thread::sync_wait [exec.sync.wait]
+
    +
  1. +

    this_thread::sync_wait and this_thread::sync_wait_with_variant are used +to block a current thread until a sender passed into it as an argument has +completed, and to obtain the values (if any) it completed with. sync_wait requires that the input sender has exactly one value completion signature.

    +
  2. +

    For any receiver rcvr created by an implementation of sync_wait and sync_wait_with_variant, the expressions get_scheduler(get_env(rcvr)) and get_delegatee_scheduler(get_env(rcvr)) shall be well-formed. For a receiver +created by the default implementation of this_thread::sync_wait, these +expressions shall return a scheduler to the same thread-safe, +first-in-first-out queue of work such that tasks scheduled to the queue +execute on the thread of the caller of sync_wait. [Note: The +scheduler for an instance of run_loop that is a local variable +within sync_wait is one valid implementation. -- end note]

    +
  3. +

    The templates sync-wait-type and sync-wait-with-variant-type are used to determine the +return types of this_thread::sync_wait and this_thread::sync_wait_with_variant. Let sync-wait-env be the type of the expression get_env(rcvr) where rcvr is an instance of the +receiver created by the default implementation of sync_wait.

    +
    template<sender_in<sync-wait-env> Sndr>
    +  using sync-wait-type =
    +    optional<value_types_of_t<Sndr, sync-wait-env, decayed-tuple, type_identity_t>>;
    +
    +template<sender_in<sync-wait-env> Sndr>
    +  using sync-wait-with-variant-type = optional<into-variant-type<Sndr, sync-wait-env>>;
    +
    +
  4. +

    The name this_thread::sync_wait denotes a customization point object. For +some subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, sync-wait-env> is false, +or if the type completion_signatures_of_t<Sndr, sync-wait-env, type-list, type_identity_t> is ill-formed, this_thread::sync_wait(sndr) is ill-formed. +Otherwise, this_thread::sync_wait(sndr) is expression-equivalent to:

    +
    apply_sender(get-domain-early(sndr), sync_wait, sndr)
    +
    +
      +
    • +

      Mandates: The type of the expression above is sync-wait-type<Sndr, sync-wait-env>.

      +
    +
  5. +

    Let sync-wait-receiver be a class type that satisfies receiver, let rcvr be an xvalue of that type, +and let crcvr be a const lvalue referring to rcvr such that get_env(crcvr) has type sync-wait-env. +If sender_in<Sndr, sync-wait-env> is false, or if the type completion_signatures_of_t<Sndr, sync-wait-env, type-list, type_identity_t> is ill-formed, +the expression sync_wait_t().apply_sender(sndr) is ill-formed; otherwise it has the following effects:

    +
      +
    1. +

      Calls connect(sndr, rcvr), resulting in an operation state op_state, then calls start(op_state).

      +
    2. +

      Blocks the current thread until a completion operation of rcvr is executed. When it is:

      +
        +
      1. +

        If set_value(rcvr, ts...) has been called, returns sync-wait-type<Sndr, sync-wait-env>{decayed-tuple<decltype(ts)...>{ts...}}. If that expression exits exceptionally, the exception is propagated to the caller of sync_wait.

        +
      2. +

        If set_error(rcvr, err) has been called, let Err be the decayed type of err. If Err is exception_ptr, calls rethrow_exception(err). Otherwise, if the Err is error_code, throws system_error(err). Otherwise, throws err.

        +
      3. +

        If set_stopped(rcvr) has been called, returns sync-wait-type<Sndr, sync-wait-env>{}.

        +
      +
    +
  6. +

    The name this_thread::sync_wait_with_variant denotes a customization point +object. For some subexpression sndr, let Sndr be the type of into_variant(sndr). If sender_in<Sndr, sync-wait-env> is false, this_thread::sync_wait_with_variant(sndr) is ill-formed. Otherwise, this_thread::sync_wait_with_variant(sndr) is expression-equivalent to:

    +
    apply_sender(get-sender-domain(sndr), sync_wait_with_variant, sndr)
    +
    +
      +
    • +

      Mandates: The type of the expression above is sync-wait-with-variant-type<Sndr, sync-wait-env>.

      +
    +
  7. +

    The expression sync_wait_with_variant_t().apply_sender(sndr) is +equal to:

    +
    if (auto opt_value = sync_wait(into_variant(sndr))) {
    +  return std::move(get<0>(*opt_value));
    +}
    +return nullopt;
    +
    +
+

11.10. execution::execute [exec.execute]

+
    +
  1. +

    execute creates fire-and-forget tasks on a specified scheduler.

    +
  2. +

    The name execute denotes a customization point object. For some subexpressions sch and f, let Sch be decltype((sch)) and F be decltype((f)). If Sch does not satisfy scheduler or F does not satisfy invocable, execute(sch, f) is ill-formed. Otherwise, execute(sch, f) is expression-equivalent to:

    +
    apply_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  execute, schedule(sch), f)
    +
    +
      +
    • +

      Mandates: The type of the expression above is void.

      +
    +
  3. +

    For some subexpressions sndr and f where F is decltype((f)), +if F does not satisfy invocable, the expression execute_t().apply_sender(sndr, f) is ill-formed; otherwise it is +expression-equivalent to start_detached(then(sndr, f)).

    +
+

11.11. Sender/receiver utilities [exec.utils]

+
    +
  1. +

    This subclause makes use of the following exposition-only entities:

    +
    // [Editorial note: copy_cvref_t as in [[P1450R3]] -- end note]
    +// Mandates: is_base_of_v<T, remove_reference_t<U>> is true
    +template<class T, class U>
    +  copy_cvref_t<U&&, T> c-style-cast(U&& u) noexcept requires decays-to<T, T> {
    +    return (copy_cvref_t<U&&, T>) std::forward<U>(u);
    +  }
    +
    +
  2. +

    + [Note: The C-style cast in + c-style-cast + is to disable accessibility checks. -- end note] +

    +
+

11.11.1. execution::receiver_adaptor [exec.utils.rcvr.adptr]

+
template<
+    class-type Derived,
+    receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
+  class receiver_adaptor;
+
+
    +
  1. +

    receiver_adaptor simplifies the implementation of one receiver type in terms of another. It defines tag_invoke overloads that forward to named members if they exist, and to the adapted receiver otherwise.

    +
  2. +

    If Base is an alias for the unspecified default template argument, then:

    +
      +
    • +

      Let HAS-BASE be false, and

      +
    • +

      Let GET-BASE(d) be d.base().

      +
    +

    otherwise, let:

    +
      +
    • +

      Let HAS-BASE be true, and

      +
    • +

      Let GET-BASE(d) be c-style-cast<receiver_adaptor<Derived, Base>>(d).base().

      +
    +

    Let BASE-TYPE(D) be the type of GET-BASE(declval<D>()).

    +
  3. +

    receiver_adaptor<Derived, Base> is equivalent to the following:

    +
    template<
    +  class-type Derived,
    +  receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
    +class receiver_adaptor {
    +  friend Derived;
    + public:
    +  using receiver_concept = receiver_t;
    +
    +  // Constructors
    +  receiver_adaptor() = default;
    +  template<class B>
    +      requires HAS-BASE && constructible_from<Base, B>
    +    explicit receiver_adaptor(B&& base) : base_(std::forward<B>(base)) {}
    +
    + private:
    +  using set_value = unspecified;
    +  using set_error = unspecified;
    +  using set_stopped = unspecified;
    +  using get_env = unspecified;
    +
    +  // Member functions
    +  template<class Self>
    +    requires HAS-BASE
    +  decltype(auto) base(this Self&& self) noexcept {
    +    return (std::forward<Self>(self).base_);
    +  }
    +
    +  // [exec.utils.rcvr.adptr.nonmembers] Non-member functions
    +  template<class... As>
    +    friend void tag_invoke(set_value_t, Derived&& self, As&&... as) noexcept;
    +
    +  template<class Err>
    +    friend void tag_invoke(set_error_t, Derived&& self, Err&& err) noexcept;
    +
    +  friend void tag_invoke(set_stopped_t, Derived&& self) noexcept;
    +
    +  friend decltype(auto) tag_invoke(get_env_t, const Derived& self)
    +      noexcept(see below);
    +
    +  [[no_unique_address]] Base base_; // present if and only if HAS-BASE is true
    +};
    +
    +
  4. +

    [Note: receiver_adaptor provides tag_invoke overloads on behalf of +the derived class Derived, which is incomplete when receiver_adaptor is +instantiated.]

    +
  5. +

    [Example:

    +
    using _int_completion =
    +  completion_signatures<set_value_t(int)>;
    +
    +template<receiver_of<_int_completion> Rcvr>
    +  class my_receiver : receiver_adaptor<my_receiver<Rcvr>, Rcvr> {
    +    friend receiver_adaptor<my_receiver, Rcvr>;
    +    void set_value() && {
    +      set_value(std::move(*this).base(), 42);
    +    }
    +   public:
    +    using receiver_adaptor<my_receiver, Rcvr>::receiver_adaptor;
    +  };
    +
    +

    -- end example]

    +
+
11.11.1.1. Non-member functions [exec.utils.rcvr.adptr.nonmembers]
+
template<class... As>
+  friend void tag_invoke(set_value_t, Derived&& self, As&&... as) noexcept;
+
+
    +
  1. +

    Let SET-VALUE-MBR be the expression std::move(self).set_value(std::forward<As>(as)...).

    +
  2. +

    Constraints: Either SET-VALUE-MBR is a valid expression or typename Derived::set_value denotes a type and callable<set_value_t, BASE-TYPE(Derived), As...> is true.

    +
  3. +

    Mandates: SET-VALUE-MBR, if that expression is valid, is not potentially-throwing.

    +
  4. +

    Effects: Equivalent to:

    +
      +
    • +

      If SET-VALUE-MBR is a valid expression, SET-VALUE-MBR;

      +
    • +

      Otherwise, set_value(GET-BASE(std::move(self)), std::forward<As>(as)...).

      +
    +
+
template<class Err>
+  friend void tag_invoke(set_error_t, Derived&& self, Err&& err) noexcept;
+
+
    +
  1. +

    Let SET-ERROR-MBR be the expression std::move(self).set_error(std::forward<Err>(err)).

    +
  2. +

    Constraints: Either SET-ERROR-MBR is a valid expression or typename Derived::set_error denotes a type and callable<set_error_t, BASE-TYPE(Derived), Err> is true.

    +
  3. +

    Mandates: SET-ERROR-MBR, if that expression is valid, is not potentially-throwing.

    +
  4. +

    Effects: Equivalent to:

    +
      +
    • +

      If SET-ERROR-MBR is a valid expression, SET-ERROR-MBR;

      +
    • +

      Otherwise, set_error(GET-BASE(std::move(self)), std::forward<Err>(err)).

      +
    +
+
friend void tag_invoke(set_stopped_t, Derived&& self) noexcept;
+
+
    +
  1. +

    Let SET-STOPPED-MBR be the expression std::move(self).set_stopped().

    +
  2. +

    Constraints: Either SET-STOPPED-MBR is a valid expression or typename Derived::set_stopped denotes a type and callable<set_stopped_t, BASE-TYPE(Derived)> is true.

    +
  3. +

    Mandates: SET-STOPPED-MBR, if that expression is valid, is not potentially-throwing.

    +
  4. +

    Effects: Equivalent to:

    +
      +
    • +

      If SET-STOPPED-MBR is a valid expression, SET-STOPPED-MBR;

      +
    • +

      Otherwise, set_stopped(GET-BASE(std::move(self))).

      +
    +
+
friend decltype(auto) tag_invoke(get_env_t, const Derived& self)
+  noexcept(see below);
+
+
    +
  1. +

    Constraints: Either self.get_env() is a valid expression or typename Derived::get_env denotes a type and callable<get_env_t, BASE-TYPE(const Derived&)> is true.

    +
  2. +

    Effects: Equivalent to:

    +
      +
    • +

      If self.get_env() is a valid expression, self.get_env();

      +
    • +

      Otherwise, get_env(GET-BASE(self)).

      +
    +
  3. +

    Remarks: The expression in the noexcept clause is:

    +
      +
    • +

      If self.get_env() is a valid expression, noexcept(self.get_env());

      +
    • +

      Otherwise, noexcept(get_env(GET-BASE(self))).

      +
    +
+

11.11.2. execution::completion_signatures [exec.utils.cmplsigs]

+
    +
  1. +

    completion_signatures is a type that encodes a set of completion signatures +([async.ops]).

    +
  2. +

    [Example:

    +
    class my_sender {
    +  using completion_signatures =
    +    completion_signatures<
    +      set_value_t(),
    +      set_value_t(int, float),
    +      set_error_t(exception_ptr),
    +      set_error_t(error_code),
    +      set_stopped_t()>;
    +};
    +
    +// Declares my_sender to be a sender that can complete by calling
    +// one of the following for a receiver expression rcvr:
    +//    set_value(rcvr)
    +//    set_value(rcvr, int{...}, float{...})
    +//    set_error(rcvr, exception_ptr{...})
    +//    set_error(rcvr, error_code{...})
    +//    set_stopped(rcvr)
    +
    +

    -- end example]

    +
  3. +

    This subclause makes use of the following exposition-only entities:

    +
    template<class Fn>
    +  concept completion-signature = see below;
    +
    +template<bool>
    +  struct indirect-meta-apply {
    +    template<template<class...> class T, class... As>
    +      using meta-apply = T<As...>; // exposition only
    +  };
    +
    +template<class...>
    +  concept always-true = true; // exposition only
    +
    +
      +
    1. +

      A type Fn satisfies completion-signature if and only if it is a function type with one of the following forms:

      +
        +
      • +

        set_value_t(Vs...), where Vs is an arbitrary parameter pack.

        +
      • +

        set_error_t(Err), where Err is an arbitrary type.

        +
      • +

        set_stopped_t()

        +
      +
    +
    template<class Tag,
    +          valid-completion-signatures Completions,
    +          template<class...> class Tuple,
    +          template<class...> class Variant>
    +  using gather-signatures = see below;
    +
    +
      +
    1. +

      Let Fns... be a template parameter pack of the arguments of the completion_signatures specialization named by Completions, let TagFns be a +template parameter pack of the function types in Fns whose return types +are Tag, and let Tsn be a template parameter +pack of the function argument types in the n-th type +in TagFns. Then, given two variadic templates Tuple and Variant, the type gather-signatures<Tag, Completions, Tuple, Variant> names the type META-APPLY(Variant, META-APPLY(Tuple, Ts0...), META-APPLY(Tuple, Ts1...), ... META-APPLY(Tuple, Tsm-1...)), where m is the size of the parameter pack TagFns and META-APPLY(T, As...) is +equivalent to:

      +
      typename indirect-meta-apply<always-true<As...>>::template meta-apply<T, As...>;
      +
      +
    2. +

      The purpose of META-APPLY is to make it +valid to use non-variadic templates as Variant and Tuple arguments to gather-signatures.

      +
    +
  4. +
    template<completion-signature... Fns>
    +  struct completion_signatures {};
    +
    +template<class Sndr,
    +          class Env = empty_env,
    +          template<class...> class Tuple = decayed-tuple,
    +          template<class...> class Variant = variant-or-empty>
    +    requires sender_in<Sndr, Env>
    +  using value_types_of_t =
    +      gather-signatures<set_value_t, completion_signatures_of_t<Sndr, Env>, Tuple, Variant>;
    +
    +template<class Sndr,
    +          class Env = empty_env,
    +          template<class...> class Variant = variant-or-empty>
    +    requires sender_in<Sndr, Env>
    +  using error_types_of_t =
    +      gather-signatures<set_error_t, completion_signatures_of_t<Sndr, Env>, type_identity_t, Variant>;
    +
    +template<class Sndr, class Env = empty_env>
    +    requires sender_in<Sndr, Env>
    +  inline constexpr bool sends_stopped =
    +      !same_as<
    +        type-list<>,
    +        gather-signatures<set_stopped_t, completion_signatures_of_t<Sndr, Env>, type-list, type-list>>;
    +
    +
+

11.11.3. execution::transform_completion_signatures [exec.utils.tfxcmplsigs]

+
    +
  1. +

    transform_completion_signatures is an alias template used to transform one +set of completion signatures into another. It takes a set of completion +signatures and several other template arguments that apply modifications to +each completion signature in the set to generate a new specialization of completion_signatures.

    +
  2. +

    [Example:

    +
    // Given a sender Sndr and an environment Env, adapt the completion
    +// signatures of Sndr by lvalue-ref qualifying the values, adding an additional
    +// exception_ptr error completion if its not already there, and leaving the
    +// other completion signatures alone.
    +template<class... Args>
    +  using my_set_value_t =
    +    completion_signatures<
    +      set_value_t(add_lvalue_reference_t<Args>...)>;
    +
    +using my_completion_signatures =
    +  transform_completion_signatures<
    +    completion_signatures_of_t<Sndr, Env>,
    +    completion_signatures<set_error_t(exception_ptr)>,
    +    my_set_value_t>;
    +
    +

    -- end example]

    +
  3. +

    This subclause makes use of the following exposition-only entities:

    +
    template<class... As>
    +  using default-set-value =
    +    completion_signatures<set_value_t(As...)>;
    +
    +template<class Err>
    +  using default-set-error =
    +    completion_signatures<set_error_t(Err)>;
    +
    +
  4. +
    template<valid-completion-signatures InputSignatures,
    +         valid-completion-signatures AdditionalSignatures =
    +             completion_signatures<>,
    +         template<class...> class SetValue = default-set-value,
    +         template<class> class SetError = default-set-error,
    +         valid-completion-signatures SetStopped =
    +             completion_signatures<set_stopped_t()>>
    +using transform_completion_signatures =
    +  completion_signatures<see below>;
    +
    +
      +
    • +

      SetValue shall name an alias template such that for any template +parameter pack As..., the type SetValue<As...> is either ill-formed +or else valid-completion-signatures<SetValue<As...>> is satisfied.

      +
    • +

      SetError shall name an alias template such that for any type Err, SetError<Err> is either ill-formed or else valid-completion-signatures<SetError<Err>> is satisfied.

      +
    +

    Then:

    +
      +
    • +

      Let Vs... be a pack of the types in the type-list named +by gether-signatures<set_value_t, InputSignatures, SetValue, type-list>.

      +
    • +

      Let Es... be a pack of the types in the type-list named by gather-signatures<set_error_t, InputSignatures, type_identity_t, error-list>, where error-list is an +alias template such that error-list<Ts...> names type-list<SetError<Ts>...>.

      +
    • +

      Let Ss name the type completion_signatures<> if gather-signatures<set_stopped_t, InputSignatures, type-list, type-list> is an alias for the type type-list<>; otherwise, SetStopped.

      +
    +

    Then:

    +
      +
    1. +

      If any of the above types are ill-formed, then transform_completion_signatures<InputSignatures, AdditionalSignatures, SetValue, SetError, SetStopped> is ill-formed,

      +
    2. +

      Otherwise, transform_completion_signatures<InputSignatures, AdditionalSignatures, SetValue, SetError, SetStopped> names the type completion_signatures<Sigs...> where Sigs... is the unique set of types in all the template arguments +of all the completion_signatures specializations in [AdditionalSignatures, Vs..., Es..., Ss].

      +
    +
+

11.12. Execution contexts [exec.ctx]

+
    +
  1. +

    This subclause specifies some execution resources on which work can be scheduled.

    +
+

11.12.1. run_loop [exec.run.loop]

+
    +
  1. +

    A run_loop is an execution resource on which work can be scheduled. It maintains a simple, thread-safe first-in-first-out queue of work. Its run() member function removes elements from the queue and executes them in a loop on whatever thread of execution calls run().

    +
  2. +

    A run_loop instance has an associated count that corresponds to the number of work items that are in its queue. Additionally, a run_loop has an associated state that can be one of starting, running, or finishing.

    +
  3. +

    Concurrent invocations of the member functions of run_loop, other than run and its destructor, do not introduce data races. The member functions pop_front, push_back, and finish execute atomically.

    +
  4. +

    [Note: Implementations are encouraged to use an intrusive queue of operation states to hold the work units to make scheduling allocation-free. — end note]

    +
    class run_loop {
    +  // [exec.run.loop.types] Associated types
    +  class run-loop-scheduler; // exposition only
    +  class run-loop-sender; // exposition only
    +  struct run-loop-opstate-base { // exposition only
    +    virtual void execute() = 0;
    +    run_loop* loop_;
    +    run-loop-opstate-base* next_;
    +  };
    +  template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
    +    using run-loop-opstate = unspecified; // exposition only
    +
    +  // [exec.run.loop.members] Member functions:
    +  run-loop-opstate-base* pop_front(); // exposition only
    +  void push_back(run-loop-opstate-base*); // exposition only
    +
    + public:
    +  // [exec.run.loop.ctor] construct/copy/destroy
    +  run_loop() noexcept;
    +  run_loop(run_loop&&) = delete;
    +  ~run_loop();
    +
    +  // [exec.run.loop.members] Member functions:
    +  run-loop-scheduler get_scheduler();
    +  void run();
    +  void finish();
    +};
    +
    +
+
11.12.1.1. Associated types [exec.run.loop.types]
+
class run-loop-scheduler;
+
+
    +
  1. +

    run-loop-scheduler is an unspecified type that models the scheduler concept.

    +
  2. +

    Instances of run-loop-scheduler remain valid until the end of the lifetime of the run_loop instance from which they were obtained.

    +
  3. +

    Two instances of run-loop-scheduler compare equal if and only if they were obtained from the same run_loop instance.

    +
  4. +

    Let sch be an expression of type run-loop-scheduler. The expression schedule(sch) is not potentially-throwing and has type run-loop-sender.

    +
+
class run-loop-sender;
+
+
    +
  1. +

    run-loop-sender is an unspecified type such that sender-of<run-loop-sender> is true. + Additionally, the types reported by its error_types associated type is exception_ptr, and the value of its sends_stopped trait is true.

    +
  2. +

    An instance of run-loop-sender remains valid until the + end of the lifetime of its associated run_loop instance.

    +
  3. +

    Let sndr be an expression of type run-loop-sender, let rcvr be an + expression such that decltype(rcvr) models the receiver_of concept, and let C be either set_value_t or set_stopped_t. Then:

    +
      +
    • +

      The expression connect(sndr, rcvr) has type run-loop-opstate<decay_t<decltype(rcvr)>> and is potentially-throwing if and only if the initialiation of decay_t<decltype(rcvr)> from rcvr is potentially-throwing.

      +
    • +

      The expression get_completion_scheduler<C>(get_env(sndr)) is not potentially-throwing, has type run-loop-scheduler, and compares equal to the run-loop-scheduler instance from which sndr was obtained.

      +
    +
+
template<receiver_of<completion_signatures<set_value_t()>> Rcvr> // arguments are not associated entities ([lib.tmpl-heads])
+  struct run-loop-opstate;
+
+
    +
  1. +

    run-loop-opstate<Rcvr> inherits unambiguously from run-loop-opstate-base.

    +
  2. +

    Let o be a non-const lvalue of type run-loop-opstate<Rcvr>, and let REC(o) be a non-const lvalue reference to an instance of type Rcvr that was initialized with the expression rcvr passed to the invocation of connect that returned o. Then:

    +
      +
    • +

      The object to which REC(o) refers remains valid for the lifetime of the object to which o refers.

      +
    • +

      The type run-loop-opstate<Rcvr> overrides run-loop-opstate-base::execute() such that o.execute() is equivalent to the following:

      +
      if (get_stop_token(REC(o)).stop_requested()) {
      +  set_stopped(std::move(REC(o)));
      +} else {
      +  set_value(std::move(REC(o)));
      +}
      +
      +
    • +

      The expression start(o) is equivalent to the following:

      +
      try {
      +  o.loop_->push_back(&o);
      +} catch(...) {
      +  set_error(std::move(REC(o)), current_exception());
      +}
      +
      +
    +
+
11.12.1.2. Constructor and destructor [exec.run.loop.ctor]
+
run_loop::run_loop() noexcept;
+
+
    +
  1. +

    Postconditions: count is 0 and state is starting.

    +
+
run_loop::~run_loop();
+
+
    +
  1. +

    Effects: If count is not 0 or if state is running, invokes terminate(). Otherwise, has no effects.

    +
+
11.12.1.3. Member functions [exec.run.loop.members]
+
run-loop-opstate-base* run_loop::pop_front();
+
+
    +
  1. +

    Effects: Blocks ([defns.block]) until one of the following conditions is true:

    +
      +
    • +

      count is 0 and state is finishing, in which case pop_front returns nullptr; or

      +
    • +

      count is greater than 0, in which case an item is removed from the front of the queue, count is decremented by 1, and the removed item is returned.

      +
    +
+
void run_loop::push_back(run-loop-opstate-base* item);
+
+
    +
  1. +

    Effects: Adds item to the back of the queue and increments count by 1.

    +
  2. +

    Synchronization: This operation synchronizes with the pop_front operation that obtains item.

    +
+
run-loop-scheduler run_loop::get_scheduler();
+
+
    +
  1. +

    Returns: an instance of run-loop-scheduler that can be used to schedule work onto this run_loop instance.

    +
+
void run_loop::run();
+
+
    +
  1. +

    Effects: Equivalent to:

    +
    while (auto* op = pop_front()) {
    +  op->execute();
    +}
    +
    +
  2. +

    Precondition: state is starting.

    +
  3. +

    Postcondition: state is finishing.

    +
  4. +

    Remarks: While the loop is executing, state is running. When state changes, it does so without introducing data races.

    +
+
void run_loop::finish();
+
+
    +
  1. +

    Effects: Changes state to finishing.

    +
  2. +

    Synchronization: This operation synchronizes with all pop_front operations on this object.

    +
+

11.13. Coroutine utilities [exec.coro.utils]

+

11.13.1. execution::as_awaitable [exec.as.awaitable]

+
    +
  1. +

    as_awaitable transforms an object into one that is awaitable within a particular coroutine. This subclause makes use of the following exposition-only entities:

    +
    template<class Sndr, class Env>
    +  using single-sender-value-type = see below;
    +
    +template<class Sndr, class Env>
    +  concept single-sender =
    +    sender_in<Sndr, Env> &&
    +    requires { typename single-sender-value-type<Sndr, Env>; };
    +
    +template<class Sndr, class Promise>
    +  concept awaitable-sender =
    +    single-sender<Sndr, env_of_t> &&
    +    sender_to<Sndr, awaitable-receiver> && // see below
    +    requires (Promise& p) {
    +      { p.unhandled_stopped() } -> convertible_to<coroutine_handle<>>;
    +    };
    +
    +template<class Sndr, class Promise>
    +  class sender-awaitable;
    +
    +
      +
    1. +

      Alias template single-sender-value-type is defined as follows:

      +
        +
      1. +

        If value_types_of_t<Sndr, Env, Tuple, Variant> would have the form Variant<Tuple<T>>, then single-sender-value-type<Sndr, Env> is an alias for type decay_t<T>.

        +
      2. +

        Otherwise, if value_types_of_t<Sndr, Env, Tuple, Variant> would have the form Variant<Tuple<>> or Variant<>, then single-sender-value-type<Sndr, Env> is an alias for type void.

        +
      3. +

        Otherwise, if value_types_of_t<Sndr, Env, Tuple, Variant> would have the form Variant<Tuple<Ts...>> where Ts is a parameter pack, then single-sender-value-type<Sndr, Env> is an alias for type std::tuple<decay_t<Ts>...>.

        +
      4. +

        Otherwise, single-sender-value-type<Sndr, Env> is ill-formed.

        +
      +
    2. +

      The type sender-awaitable<Sndr, Promise> is equivalent to the following:

      +
      template<class Sndr, class Promise> // arguments are not associated entities ([lib.tmpl-heads])
      +class sender-awaitable {
      +  struct unit {};
      +  using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>;
      +  using result_t = conditional_t<is_void_v<value_t>, unit, value_t>;
      +  struct awaitable-receiver;
      +
      +  variant<monostate, result_t, exception_ptr> result_{};
      +  connect_result_t<Sndr, awaitable-receiver> state_;
      +
      + public:
      +  sender-awaitable(Sndr&& sndr, Promise& p);
      +  bool await_ready() const noexcept { return false; }
      +  void await_suspend(coroutine_handle<Promise>) noexcept { start(state_); }
      +  value_t await_resume();
      +};
      +
      +
        +
      1. +

        awaitable-receiver is equivalent to the following:

        +
        struct awaitable-receiver {
        +  using receiver_concept = receiver_t;
        +  variant<monostate, result_t, exception_ptr>* result_ptr_;
        +  coroutine_handle<Promise> continuation_;
        +  // ... see below
        +};
        +
        +

        Let rcvr be an rvalue expression of type awaitable-receiver, let crcvr be a const lvalue that refers to rcvr, let vs be a parameter pack of types Vs..., and let err be an arbitrary expression of type Err. Then:

        +
          +
        1. +

          If constructible_from<result_t, Vs...> is satisfied, the expression set_value(rcvr, vs...) is equivalent to:

          +
          try {
          +  rcvr.result_ptr_->emplace<1>(vs...);
          +} catch(...) {
          +  rcvr.result_ptr_->emplace<2>(current_exception());
          +}
          +rcvr.continuation_.resume();
          +
          +

          Otherwise, set_value(rcvr, vs...) is ill-formed.

          +
        2. +

          The expression set_error(rcvr, err) is equivalent to:

          +
          rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err));
          +rcvr.continuation_.resume();
          +
          +

          where AS-EXCEPT-PTR(err) is:

          +
            +
          1. +

            err if decay_t<Err> names the same type as exception_ptr,

            +
          2. +

            Otherwise, make_exception_ptr(system_error(err)) if decay_t<Err> names the same type as error_code,

            +
          3. +

            Otherwise, make_exception_ptr(err).

            +
          +
        3. +

          The expression set_stopped(rcvr) is equivalent to static_cast<coroutine_handle<>>(rcvr.continuation_.promise().unhandled_stopped()).resume().

          +
        4. +

          For any expression tag whose type satisfies forwarding-query and for any pack of subexpressions as, tag_invoke(tag, get_env(crcvr), as...) is expression-equivalent to tag(get_env(as_const(crcvr.continuation_.promise())), as...) when that expression is well-formed.

          +
        +
      2. +

        sender-awaitable::sender-awaitable(Sndr&& sndr, Promise& p)

        +
          +
        • +

          Effects: initializes state_ with connect(std::forward<Sndr>(sndr), awaitable-receiver{&result_, coroutine_handle<Promise>::from_promise(p)}).

          +
        +
      3. +

        value_t sender-awaitable::await_resume()

        +
          +
        • +

          Effects: equivalent to:

          +
          if (result_.index() == 2)
          +  rethrow_exception(get<2>(result_));
          +if constexpr (!is_void_v<value_t>)
          +  return std::forward<value_t>(get<1>(result_));
          +
          +
        +
      +
    +
  2. +

    as_awaitable is a customization point object. For some subexpressions expr and p where p is an lvalue, Expr names the type decltype((expr)) and Promise names the type decltype((p)), as_awaitable(expr, p) is expression-equivalent to the following:

    +
      +
    1. +

      tag_invoke(as_awaitable, expr, p) if that expression is well-formed.

      +
        +
      • +

        Mandates: is-awaitable<A, Promise> is true, where A is the type of the tag_invoke expression above.

        +
      +
    2. +

      Otherwise, expr if is-awaitable<Expr, U> is true, where U is an unspecified class type that +lacks a member named await_transform. The +condition is not is-awaitable<Expr, Promise> as that +creates the potential for constraint recursion.

      +
        +
      • +

        Preconditions: is-awaitable<Expr, Promise> is true and the expression co_await expr in a coroutine with promise +type U is expression-equivalent to the same +expression in a coroutine with promise type Promise.

        +
      +
    3. +

      Otherwise, sender-awaitable{expr, p} if awaitable-sender<Expr, Promise> is true.

      +
    4. +

      Otherwise, expr.

      +
    +
+

11.13.2. execution::with_awaitable_senders [exec.with.awaitable.senders]

+
    +
  1. +

    with_awaitable_senders, when used as the base class of a coroutine promise type, makes senders awaitable in that coroutine type.

    +

    In addition, it provides a default implementation of unhandled_stopped() such that if a sender completes by calling set_stopped, it is treated as if an uncatchable "stopped" exception were thrown from the await-expression. In practice, the coroutine is never resumed, and the unhandled_stopped of the coroutine caller’s promise type is called.

    +
    template<class-type Promise>
    +  struct with_awaitable_senders {
    +    template<OtherPromise>
    +      requires (!same_as<OtherPromise, void>)
    +    void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
    +
    +    coroutine_handle<> continuation() const noexcept { return continuation_; }
    +
    +    coroutine_handle<> unhandled_stopped() noexcept {
    +      return stopped_handler_(continuation_.address());
    +    }
    +
    +    template<class Value>
    +    see below await_transform(Value&& value);
    +
    +   private:
    +    // exposition only
    +    [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
    +      terminate();
    +    }
    +    coroutine_handle<> continuation_{}; // exposition only
    +    // exposition only
    +    coroutine_handle<> (*stopped_handler_)(void*) noexcept = &default_unhandled_stopped;
    +  };
    +
    +
  2. +

    void set_continuation(coroutine_handle<OtherPromise> h) noexcept

    +
      +
    • +

      Effects: equivalent to:

      +
      continuation_ = h;
      +if constexpr ( requires(OtherPromise& other) { other.unhandled_stopped(); } ) {
      +  stopped_handler_ = [](void* p) noexcept -> coroutine_handle<> {
      +    return coroutine_handle<OtherPromise>::from_address(p)
      +      .promise().unhandled_stopped();
      +  };
      +} else {
      +  stopped_handler_ = default_unhandled_stopped;
      +}
      +
      +
    +
  3. +

    call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value)

    +
      +
    • +

      Effects: equivalent to:

      +
      return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));
      +
      +
    +
+
+ +

Index

+

Terms defined by this specification

+ +

References

+

Informative References

+
+
[CWG2517] +
Richard Smith. Useless restriction on use of parameter in constraint-expression. 10 June 2019. open. URL: https://wg21.link/cwg2517 +
[HPX] +
Hartmut Kaiser; et al. HPX - The C++ Standard Library for Parallelism and Concurrency. URL: https://doi.org/10.21105/joss.02352 +
[N4885] +
Thomas Köppe. Working Draft, Standard for Programming Language C++. 17 March 2021. URL: https://wg21.link/n4885 +
[P0443R14] +
Jared Hoberock, Michael Garland, Chris Kohlhoff, Chris Mysen, H. Carter Edwards, Gordon Brown, D. S. Hollman. A Unified Executors Proposal for C++. 15 September 2020. URL: https://wg21.link/p0443r14 +
[P0981R0] +
Richard Smith, Gor Nishanov. Halo: coroutine Heap Allocation eLision Optimization: the joint response. 18 March 2018. URL: https://wg21.link/p0981r0 +
[P1056R1] +
Lewis Baker, Gor Nishanov. Add lazy coroutine (coroutine task) type. 7 October 2018. URL: https://wg21.link/p1056r1 +
[P1895R0] +
Lewis Baker, Eric Niebler, Kirk Shoop. tag_invoke: A general pattern for supporting customisable functions. 8 October 2019. URL: https://wg21.link/p1895r0 +
[P1897R3] +
Lee Howes. Towards C++23 executors: A proposal for an initial set of algorithms. 16 May 2020. URL: https://wg21.link/p1897r3 +
[P2175R0] +
Lewis Baker. Composable cancellation for sender-based async operations. 15 December 2020. URL: https://wg21.link/p2175r0 +
[P2280r2] +
Barry Revzin. Using unknown references in constant expressions. 15 May 2021. URL: https://wg21.link/p2280r2 +
+ + + + + + + + + + + + + + \ No newline at end of file From b9d68fc644f2ed6ee265e0490ea07e673c1305e9 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 23 Feb 2024 16:43:26 -0800 Subject: [PATCH 26/89] fix typo, bump revision --- execution.bs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index ba8095d..f50fd2f 100644 --- a/execution.bs +++ b/execution.bs @@ -2,7 +2,7 @@ Title: `std::execution` H1: std::execution Shortname: D2300 -Revision: 8 +Revision: 9 Status: D Group: WG21 Audience: SG1, LEWG @@ -7783,7 +7783,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> Then: * Let `Vs...` be a pack of the types in the type-list named - by gether-signatures<set_value_t, InputSignatures, SetValue, type-list>. + by gather-signatures<set_value_t, InputSignatures, SetValue, type-list>. * Let `Es...` be a pack of the types in the type-list named by gather-signatures<set_error_t, InputSignatures, From cb283ccf0d83b4caeb664f381bd208e74eecd0d4 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 23 Feb 2024 16:45:04 -0800 Subject: [PATCH 27/89] fix github urls --- execution.bs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index f50fd2f..ce1737f 100644 --- a/execution.bs +++ b/execution.bs @@ -16,8 +16,8 @@ Editor: Michael Garland, mgarland@nvidia.com Editor: Eric Niebler, eric.niebler@gmail.com Editor: Bryce Adelstein Lelbach, brycelelbach@gmail.com URL: https://wg21.link/P2300 -!Source: GitHub -Issue Tracking: GitHub https://github.com/brycelelbach/wg21_p2300_execution/issues +!Source: GitHub +Issue Tracking: GitHub https://github.com/cplusplus/sender-receiver/issues Metadata Order: Editor, This Version, Source, Issue Tracking, Project, Audience Markup Shorthands: markdown yes Toggle Diffs: no From cc305249c82a31ef397811b91ecaeb38cd2bcabf Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 28 Feb 2024 17:32:29 -0800 Subject: [PATCH 28/89] `receiver_adaptor`'s customization of `get_env` should be unconditionally `noexcept` --- execution.bs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/execution.bs b/execution.bs index ce1737f..a310df2 100644 --- a/execution.bs +++ b/execution.bs @@ -7512,8 +7512,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> friend void tag_invoke(set_stopped_t, Derived&& self) noexcept; - friend decltype(auto) tag_invoke(get_env_t, const Derived& self) - noexcept(see below); + friend decltype(auto) tag_invoke(get_env_t, const Derived& self) noexcept; [[no_unique_address]] Base base_; // present if and only if HAS-BASE is true }; @@ -7593,24 +7592,19 @@ template<class Domain, class Tag, sender Sndr, class... Args> * Otherwise, set_stopped(GET-BASE(std::move(self))).
-    friend decltype(auto) tag_invoke(get_env_t, const Derived& self)
-      noexcept(see below);
+    friend decltype(auto) tag_invoke(get_env_t, const Derived& self) noexcept;
     
1. Constraints: Either `self.get_env()` is a valid expression or `typename Derived::get_env` denotes a type and callable<get_env_t, BASE-TYPE(const Derived&)> is `true`. - 2. Effects: Equivalent to: + 2. Mandates: `noexcept(self.get_env())` is `true` if it is a valid expression. + + 3. Effects: Equivalent to: * If `self.get_env()` is a valid expression, `self.get_env()`; * Otherwise, get_env(GET-BASE(self)). - 3. Remarks: The expression in the `noexcept` clause is: - - * If `self.get_env()` is a valid expression, `noexcept(self.get_env())`; - - * Otherwise, noexcept(get_env(GET-BASE(self))). - ### `execution::completion_signatures` [exec.utils.cmplsigs] ### {#spec-execution.snd_rec_utils.completion_sigs} 1. `completion_signatures` is a type that encodes a set of completion signatures From 282945612692203d389c553648b0ebdbc74ae473 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 5 Mar 2024 16:37:47 -0800 Subject: [PATCH 29/89] fix copy/pasta --- execution.bs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index a310df2..96d2134 100644 --- a/execution.bs +++ b/execution.bs @@ -5627,9 +5627,9 @@ template<class Domain, sender Sndr, queryable Env> constexpr decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
-3. Returns: `dom.transform_sender(std::forward(sndr), std::forward(env))` if that +2. Returns: `dom.transform_env(std::forward(sndr), std::forward(env))` if that expression is well-formed; otherwise, - `default_domain().transform_sender(std::forward(sndr), std::forward(env))`. + `default_domain().transform_env(std::forward(sndr), std::forward(env))`. ### `execution::apply_sender` [exec.snd.apply] ### {#spec-execution.apply_sender} From 3565321b4b42d3a10c229610da22d446b254607c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 13 Mar 2024 17:33:25 -0700 Subject: [PATCH 30/89] add missing italics around exposition-only identifier --- execution.bs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/execution.bs b/execution.bs index 96d2134..3842a7e 100644 --- a/execution.bs +++ b/execution.bs @@ -5880,9 +5880,10 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template<>
     struct impls-for<tag_t<read>> : default-impls {
-      static constexpr auto start = [](auto query, auto& rcvr) noexcept -> void {
-        TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
-      };
+      static constexpr auto start =
+        [](auto query, auto& rcvr) noexcept -> void {
+          TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
+        };
     };
     
@@ -6130,7 +6131,6 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(schedule_from, sch, sndr));
- 4. The exposition-only class template impls-for ([exec.snd.general]) is specialized for `schedule_from_t` as follows: From 5b8bd38b9cacf9f70c587b1cb7ae2d3a9dc9bfef Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Mon, 18 Mar 2024 09:10:12 -0700 Subject: [PATCH 31/89] feedback from LWG wording review Mar 18: `start_detached` --- execution.bs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/execution.bs b/execution.bs index 3842a7e..c7938c1 100644 --- a/execution.bs +++ b/execution.bs @@ -7235,7 +7235,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     transform_sender(
-      get-sender-domain(sndr),
+      get-domain-early(sndr),
       make-sender(stopped_as_optional, {}, sndr))
     
@@ -7263,7 +7263,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     transform_sender(
-      get-sender-domain(sndr),
+      get-domain-early(sndr),
       make-sender(stopped_as_error, err, sndr))
     
@@ -7288,13 +7288,15 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. The name `start_detached` denotes a customization point object. For some subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If `sender_in` is `false`, `start_detached` is ill-formed. - Otherwise, the expression `start_detached(sndr)` is expression-equivalent to: + Otherwise, the expression `start_detached(sndr)` is expression-equivalent to + the following except that `sndr` is evaluated only once:
-    apply_sender(get-sender-domain(sndr), start_detached, sndr)
+    apply_sender(get-domain-early(sndr), start_detached, sndr)
     
- * Mandates: The type of the expression above is `void`. + * Mandates: same_as<decltype(e), void> is + `true` where e is the expression above. If the expression above does not eagerly start the sender `sndr` after connecting it with a receiver that ignores value and stopped completion @@ -7314,7 +7316,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> friend void tag_invoke(set_value_t, detached-receiver&& self) noexcept { delete self.op; } friend void tag_invoke(set_error_t, detached-receiver&&, auto&&) noexcept { terminate(); } friend void tag_invoke(set_stopped_t, detached-receiver&& self) noexcept { delete self.op; } - friend empty_env tag_invoke(get_env_t, const detached-receiver&) { return {}; } + friend empty_env tag_invoke(get_env_t, const detached-receiver&) noexcept { return {}; } }; struct detached-operation { @@ -7328,8 +7330,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> 4. If sender_to<Sndr, detached-receiver> is `false`, the expression `start_detached.apply_sender(sndr)` is ill-formed; otherwise, it is - expression-equivalent to start(*new - detached-operation(sndr)). + expression-equivalent to start((new + detached-operation(sndr))->op). #### `this_thread::sync_wait` [exec.sync.wait] #### {#spec-execution.senders.consumers.sync_wait} @@ -7401,7 +7403,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> `this_thread::sync_wait_with_variant(sndr)` is expression-equivalent to:
-    apply_sender(get-sender-domain(sndr), sync_wait_with_variant, sndr)
+    apply_sender(get-domain-early(sndr), sync_wait_with_variant, sndr)
     
* Mandates: The type of the expression above is sync-wait-with-variant-type<Sndr, sync-wait-env>. From fc38e351068926805ec93de67f6f413cd3dbbf6c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Mon, 18 Mar 2024 15:50:06 -0700 Subject: [PATCH 32/89] respecify sync_wait[_with_variant] --- execution.bs | 232 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 169 insertions(+), 63 deletions(-) diff --git a/execution.bs b/execution.bs index c7938c1..88b8c1a 100644 --- a/execution.bs +++ b/execution.bs @@ -1173,7 +1173,7 @@ The changes since R6 are as follows: * Make it valid to pass non-variadic templates to the exposition-only alias template gather-signatures, fixing the definitions of `value_types_of_t`, `error_types_of_t`, and the exposition-only alias - template sync-wait-type. + template sync-wait-result-type. * Removed the query forwarding from `receiver_adaptor` that was inadvertantly left over from a previous edit. * When adapting a sender to an awaitable with `as_awaitable`, the sender's @@ -3855,6 +3855,18 @@ template<class C> respectively, MATCHING-SIG(F1, F2) is `true` if and only if `same_as` is `true`. + 4. For a subexpression `err`, let `Err` be `decltype((err))` and let + AS-EXCEPT-PTR(err) be: + + 1. `err` if `decay_t` denotes the type `exception_ptr`. + + - *Mandates:* `err != exception_ptr()` is `true` + + 2. Otherwise, `make_exception_ptr(system_error(err))` if `decay_t` denotes the type `error_code`, + + 3. Otherwise, `make_exception_ptr(err)`. + + ## Queries and queryables [exec.queryable] ## {#spec-execution.queryable} ### General [exec.queryable.general] ### {#spec-execution.queryable.general} @@ -4440,9 +4452,9 @@ namespace std::this_thread { struct sync-wait-env; // exposition only template<class Sndr> requires sender_in<Sndr, sync-wait-env> - using sync-wait-type = see below; // exposition only + using sync-wait-result-type = see below; // exposition only template<class Sndr> - using sync-wait-with-variant-type = see below; // exposition only + using sync-wait-with-variant-result-type = see below; // exposition only struct sync_wait_t; struct sync_wait_with_variant_t; @@ -6063,7 +6075,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, `transfer(sndr, sch)` is ill-formed. - + 3. Otherwise, the expression `transfer(sndr, sch)` is expression-equivalent to:
@@ -7051,7 +7063,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                   
3. Otherwise, evaluates: - +
                 on_stop.reset();
                 set_stopped(std::move(rcvr));
@@ -7336,88 +7348,190 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 #### `this_thread::sync_wait` [exec.sync.wait] #### {#spec-execution.senders.consumers.sync_wait}
 
 1. `this_thread::sync_wait` and `this_thread::sync_wait_with_variant` are used
-    to block a current thread until a sender passed into it as an argument has
-    completed, and to obtain the values (if any) it completed with. `sync_wait`
-    requires that the input sender has exactly one value completion signature.
-
-2. For any receiver `rcvr` created by an implementation of `sync_wait` and
-    `sync_wait_with_variant`, the expressions `get_scheduler(get_env(rcvr))` and
-    `get_delegatee_scheduler(get_env(rcvr))` shall be well-formed. For a receiver
-    created by the default implementation of `this_thread::sync_wait`, these
-    expressions shall return a scheduler to the same thread-safe,
-    first-in-first-out queue of work such that tasks scheduled to the queue
-    execute on the thread of the caller of `sync_wait`. [Note: The
-    scheduler for an instance of `run_loop` that is a local variable
-    within `sync_wait` is one valid implementation. -- end note]
-
-3. The templates sync-wait-type and
-    sync-wait-with-variant-type are used to determine the
-    return types of `this_thread::sync_wait` and
-    `this_thread::sync_wait_with_variant`. Let sync-wait-env
-    be the type of the expression `get_env(rcvr)` where `rcvr` is an instance of the
-    receiver created by the default implementation of `sync_wait`.
+    to block the current thread of execution until the specified sender
+    completes and to return its async result. `sync_wait` mandates that the
+    input sender has exactly one value completion signature.
+
+2. Let sync-wait-env be the following exposition-only class
+    type:
+
+    
+    template<class Tag>
+    concept get-sched-query = // exposition only
+      one-of<Tag, execution::get_scheduler_t, execution::get_delegatee_scheduler_t>;
+
+    struct sync-wait-env {
+      execution::run_loop* loop; // exposition only
+
+      friend auto tag_invoke(get-sched-query auto, sync-wait-env self) noexcept {
+        return self.loop->get_scheduler();
+      }
+    };
+    
+ +3. Let sync-wait-result-type and + sync-wait-with-variant-result-type be exposition-only + template aliases that are defined as follows:
     template<sender_in<sync-wait-env> Sndr>
-      using sync-wait-type =
+      using sync-wait-result-type =
         optional<value_types_of_t<Sndr, sync-wait-env, decayed-tuple, type_identity_t>>;
 
     template<sender_in<sync-wait-env> Sndr>
-      using sync-wait-with-variant-type = optional<into-variant-type<Sndr, sync-wait-env>>;
+      using sync-wait-with-variant-result-type =
+        optional<into-variant-type<Sndr, sync-wait-env>>; // see [exec.into.variant]
     
-4. The name `this_thread::sync_wait` denotes a customization point object. For - some subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If - sender_in<Sndr, sync-wait-env> is `false`, - or if the type completion_signatures_of_t<Sndr, sync-wait-env, type-list, type_identity_t> is ill-formed, - `this_thread::sync_wait(sndr)` is ill-formed. - Otherwise, `this_thread::sync_wait(sndr)` is expression-equivalent to: + +4. The name `this_thread::sync_wait` denotes a customization point object. For a + subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If + sender_in<Sndr, sync-wait-env> is `false`, the + expression `this_thread::sync_wait(sndr)` is ill-formed. Otherwise, it is + expression-equivalent to the following, except that `sndr` is evaluated only + once: + +
+      apply_sender(get-domain-early(sndr), sync_wait, sndr)
+      
+ + Mandates: + + * The type sync-wait-result-type<Sndr> is well-formed. + + * same_as<decltype(e), + sync-wait-result-type<Sndr>> is `true`, where + e is the expression above. + +5. Let sync-wait-receiver be the following exposition-only class template:
-    apply_sender(get-domain-early(sndr), sync_wait, sndr)
+    template<class Sndr>
+    struct sync-wait-state {
+      run_loop loop;
+      exception_ptr error;
+      sync-wait-result-type<Sndr> result;
+    };
+
+    template<class Sndr>
+    struct sync-wait-receiver {
+      using receiver_concept = receiver_t;
+      sync-wait-state<Sndr>* state; // exposition only
+
+      template<class Tag, class... Ts>
+      void complete(Tag, Ts&&... ts) noexcept; // exposition only
+
+      template<completion-tag Tag, class... Ts>
+      friend void tag_invoke(Tag, sync-wait-receiver&& self, Ts&&... ts) noexcept {
+        self.complete(Tag(), std::forward<Ts>(ts)...);
+        self.state->loop.finish();
+      }
+
+      friend sync-wait-env tag_invoke(get_env_t, const sync-wait-receiver& self) noexcept {
+        return {&self.state->loop};
+      }
+    };
     
- * Mandates: The type of the expression above is sync-wait-type<Sndr, sync-wait-env>. + 1. The member sync-wait-receiver::complete behaves as follows: + + 1. If `Tag` is `set_value_t`, evaluates: + +
+            try {
+              state->result.emplace(std::forward<Ts>(ts)...);
+            } catch (...) {
+              state->error = current_exception();
+            }
+            
+ + 2. Otherwise, if `Tag` is `set_error_t`, evaluates: + +
+            state->error = AS-EXCEPT-PTR(std::forward(ts)...); // see [exec.general]
+            
+ + 3. Otherwise, does nothing. + +6. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If + sender_in<Sndr, sync-wait-env> is `false`, the + expression `sync_wait.apply_sender(sndr)` is ill-formed; otherwise, it is + equivalent to: + +
+        sync-wait-state<Sndr> state;
+        auto op = connect(sndr, sync-wait-receiver<Sndr>{&state});
+        start(op);
+
+        state.loop.run();
+        if (state.error) {
+          rethrow_exception(std::move(state.error));
+        }
+        return std::move(state.result);
+        
-5. Let sync-wait-receiver be a class type that satisfies `receiver`, let `rcvr` be an xvalue of that type, - and let `crcvr` be a const lvalue referring to `rcvr` such that `get_env(crcvr)` has type sync-wait-env. - If sender_in<Sndr, sync-wait-env> is `false`, or if the type - completion_signatures_of_t<Sndr, sync-wait-env, type-list, type_identity_t> is ill-formed, - the expression `sync_wait_t().apply_sender(sndr)` is ill-formed; otherwise it has the following effects: +7. The behavior of `this_thread::sync_wait(sndr)` is undefined unless: - 1. Calls `connect(sndr, rcvr)`, resulting in an operation state `op_state`, then calls `start(op_state)`. + 1. It blocks the current thread of execution with forward progress guarantee + delegation ([intro.progress]) until the specified sender completes, and - 2. Blocks the current thread until a completion operation of `rcvr` is executed. When it is: + 2. It returns the specified sender's async results as follows: - 1. If `set_value(rcvr, ts...)` has been called, returns sync-wait-type<Sndr, sync-wait-env>{decayed-tuple<decltype(ts)...>{ts...}}. If that expression exits exceptionally, the exception is propagated to the caller of `sync_wait`. + 1. For a value completion, the result datums are returned + in a `tuple` in an engaged `optional` object. - 2. If `set_error(rcvr, err)` has been called, let `Err` be the decayed type of `err`. If `Err` is `exception_ptr`, calls `rethrow_exception(err)`. Otherwise, if the `Err` is `error_code`, throws `system_error(err)`. Otherwise, throws `err`. + 2. For an error completion, the result datum is rethrown. - 3. If `set_stopped(rcvr)` has been called, returns sync-wait-type<Sndr, sync-wait-env>{}. + 3. For a stopped completion, a disengaged `optional` object is returned. -6. The name `this_thread::sync_wait_with_variant` denotes a customization point - object. For some subexpression `sndr`, let `Sndr` be the type of +8. The name `this_thread::sync_wait_with_variant` denotes a customization point + object. For a subexpression `sndr`, let `Sndr` be the type of `into_variant(sndr)`. If sender_in<Sndr, sync-wait-env> is `false`, - `this_thread::sync_wait_with_variant(sndr)` is ill-formed. Otherwise, - `this_thread::sync_wait_with_variant(sndr)` is expression-equivalent to: + `this_thread::sync_wait_with_variant(sndr)` is ill-formed. Otherwise, it is + expression-equivalent to the following, except `sndr` is evaluated only + once:
     apply_sender(get-domain-early(sndr), sync_wait_with_variant, sndr)
     
- * Mandates: The type of the expression above is sync-wait-with-variant-type<Sndr, sync-wait-env>. + Mandates: + + - The type sync-wait-with-variant-result-type<Sndr> is + well-formed. -7. The expression `sync_wait_with_variant_t().apply_sender(sndr)` is - equal to: + - same_as<decltype(e), + sync-wait-with-variant-result-type<Sndr>> is `true`, + where e is the expression above. + +9. If sender_in<Sndr, sync-wait-env> is `false`, the + expression `sync_wait_with_variant.apply_sender(sndr)` is ill-formed. + Otherwise, it is equivalent to:
+        using result_type = sync-wait-with-variant-result-type<Sndr>;
         if (auto opt_value = sync_wait(into_variant(sndr))) {
-          return std::move(get<0>(*opt_value));
+          return result_type(std::move(get<0>(*opt_value)));
         }
-        return nullopt;
+        return result_type(nullopt);
         
+10. The behavior of `this_thread::sync_wait_with_variant(sndr)` is undefined unless: + + 1. It blocks the current thread of execution with forward progress guarantee + delegation ([intro.progress]) until the specified sender completes, and + + 2. It returns the specified sender's async results as follows: + + 1. For a value completion, the result datums are returned + in a `variant` of `tuple`s in an engaged `optional` object. + + 2. For an error completion, the result datum is rethrown. + + 3. For a stopped completion, a disengaged `optional` object is returned. + + ## `execution::execute` [exec.execute] ## {#spec-execution.execute} 1. `execute` creates fire-and-forget tasks on a specified scheduler. @@ -8065,18 +8179,10 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. The expression `set_error(rcvr, err)` is equivalent to:
-                  rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err));
+                  rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
                   rcvr.continuation_.resume();
                   
- where AS-EXCEPT-PTR(err) is: - - 1. `err` if `decay_t` names the same type as `exception_ptr`, - - 2. Otherwise, `make_exception_ptr(system_error(err))` if `decay_t` names the same type as `error_code`, - - 3. Otherwise, `make_exception_ptr(err)`. - 3. The expression `set_stopped(rcvr)` is equivalent to static_cast<coroutine_handle<>>(rcvr.continuation_.promise().unhandled_stopped()).resume(). From ddc76cf1113064f2c855fa32f55b8e75d6c4779e Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Mon, 18 Mar 2024 16:16:21 -0700 Subject: [PATCH 33/89] consistency fixes --- execution.bs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/execution.bs b/execution.bs index 88b8c1a..72abe75 100644 --- a/execution.bs +++ b/execution.bs @@ -7407,7 +7407,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template<class Sndr>
-    struct sync-wait-state {
+    struct sync-wait-state { // exposition only
       run_loop loop;
       exception_ptr error;
       sync-wait-result-type<Sndr> result;
@@ -7454,7 +7454,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         3. Otherwise, does nothing.
 
 6. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If
-    sender_in<Sndr, sync-wait-env> is `false`, the
+    sender_to<Sndr, sync-wait-receiver<Sndr>> is `false`, the
     expression `sync_wait.apply_sender(sndr)` is ill-formed; otherwise, it is
     equivalent to:
 
@@ -7505,7 +7505,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         sync-wait-with-variant-result-type<Sndr>> is `true`,
         where e is the expression above.
 
-9. If sender_in<Sndr, sync-wait-env> is `false`, the
+9. If callable<sync_wait_t, Sndr> is `false`, the
     expression `sync_wait_with_variant.apply_sender(sndr)` is ill-formed.
     Otherwise, it is equivalent to:
 

From 48c85a557cfb0dd15590e0b644689924689f720d Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Mon, 18 Mar 2024 18:38:48 -0700
Subject: [PATCH 34/89] second round of changes on `sync_wait[_with_variant]`

---
 execution.bs | 34 +++++++++++++++++++++++-----------
 1 file changed, 23 insertions(+), 11 deletions(-)

diff --git a/execution.bs b/execution.bs
index 72abe75..90dd3d4 100644
--- a/execution.bs
+++ b/execution.bs
@@ -7371,7 +7371,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
 3. Let sync-wait-result-type and
     sync-wait-with-variant-result-type be exposition-only
-    template aliases that are defined as follows:
+    template aliases defined as follows:
 
     
     template<sender_in<sync-wait-env> Sndr>
@@ -7401,9 +7401,11 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
         * same_as<decltype(e),
             sync-wait-result-type<Sndr>> is `true`, where
-            e is the expression above.
+            e is `apply_sender` the expression above.
 
-5. Let sync-wait-receiver be the following exposition-only class template:
+5. Let sync-wait-state and
+    sync-wait-receiver be the following exposition-only class
+    templates:
 
     
     template<class Sndr>
@@ -7473,7 +7475,12 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 7. The behavior of `this_thread::sync_wait(sndr)` is undefined unless:
 
     1. It blocks the current thread of execution with forward progress guarantee
-        delegation ([intro.progress]) until the specified sender completes, and
+        delegation ([intro.progress]) until the specified sender completes.
+        The default implementation of `sync_wait`
+        achieves forward progress guarantee delegation by providing a `run_loop`
+        scheduler via the `get_delegatee_scheduler` query on the
+        sync-wait-receiver's environment. The `run_loop`
+        is driven by the current thread of execution.
 
     2. It returns the specified sender's async results as follows:
 
@@ -7520,7 +7527,10 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 10. The behavior of `this_thread::sync_wait_with_variant(sndr)` is undefined unless:
 
     1. It blocks the current thread of execution with forward progress guarantee
-        delegation ([intro.progress]) until the specified sender completes, and
+        delegation ([intro.progress]) until the specified sender completes.
+        The default implementation of `sync_wait_with_variant`
+        achieves forward progress guarantee delegation by relying on the
+        forward progress guarantee delegation provided by `sync_wait`.
 
     2. It returns the specified sender's async results as follows:
 
@@ -7531,13 +7541,15 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
         3. For a stopped completion, a disengaged `optional` object is returned.
 
-
 ## `execution::execute` [exec.execute] ## {#spec-execution.execute}
 
-1. `execute` creates fire-and-forget tasks on a specified scheduler.
+1. `execute` executes a specified callable object on a specified scheduler.
 
-2. The name `execute` denotes a customization point object. For some subexpressions `sch` and `f`, let `Sch` be `decltype((sch))` and `F` be `decltype((f))`. If `Sch` does not satisfy `scheduler` or `F` does not satisfy `invocable`,
-    `execute(sch, f)` is ill-formed. Otherwise, `execute(sch, f)` is expression-equivalent to:
+2. The name `execute` denotes a customization point object. For some
+    subexpressions `sch` and `f`, let `Sch` be `decltype((sch))` and `F` be the
+    decayed type of `f`. If `Sch` does not satisfy `scheduler` or `F` does not
+    satisfy `invocable`, `execute(sch, f)` is ill-formed. Otherwise,
+    `execute(sch, f)` is expression-equivalent to:
 
     
     apply_sender(
@@ -7546,9 +7558,9 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     
* Mandates: The type of the expression above is `void`. -3. For some subexpressions `sndr` and `f` where `F` is `decltype((f))`, +3. For some subexpressions `sndr` and `f` where `F` is the decayed type of `f`, if `F` does not satisfy `invocable`, the expression - `execute_t().apply_sender(sndr, f)` is ill-formed; otherwise it is + `execute.apply_sender(sndr, f)` is ill-formed; otherwise it is expression-equivalent to `start_detached(then(sndr, f))`. ## Sender/receiver utilities [exec.utils] ## {#spec-execution.snd_rec_utils} From 10c4bca079e96802d0999a2721bb3783321baf95 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Mon, 18 Mar 2024 19:13:07 -0700 Subject: [PATCH 35/89] update default_domain, transform_[sender|env], apply_sender --- execution.bs | 136 +++++++++++++++++++++++---------------------------- 1 file changed, 62 insertions(+), 74 deletions(-) diff --git a/execution.bs b/execution.bs index 90dd3d4..d12a9e8 100644 --- a/execution.bs +++ b/execution.bs @@ -5541,14 +5541,12 @@ enum class forward_progress_guarantee {
 struct default_domain {
-  template <sender Sndr>
-    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr) noexcept(see below);
-
-  template <sender Sndr, queryable Env>
-    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env& env) noexcept(see below);
+  template <sender Sndr, queryable... Env>
+      requires (sizeof...(Env) <= 1)
+    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
 
   template <sender Sndr, queryable Env>
-    static constexpr decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+    static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
 
   template<class Tag, sender Sndr, class... Args>
     static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
@@ -5558,90 +5556,86 @@ struct default_domain {
 #### Static members [exec.domain.default.statics] #### {#spec-execution.default_domain.statics}
 
 
-template <sender Sndr>
-  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr) noexcept(see below);
+template <sender Sndr, queryable... Env>
+    requires (sizeof...(Env) <= 1)
+  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
 
-1. Returns: `tag_of_t().transform_sender(std::forward(sndr))` - if that expression is well-formed; otherwise, `std::forward(sndr)`. +1. Let e be the expression + `tag_of_t().transform_sender(std::forward(sndr), env...)` if that + expression is well-formed; otherwise, `std::forward(sndr)`. -2. Remarks: The exception specification is equivalent to: +2. Returns: e. -
-    noexcept(tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr)))
-    
- - if that expression is well-formed; otherwise, `true`; +3. Remarks: The exception specification is equivalent to noexcept(e).
 template <sender Sndr, queryable Env>
-  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr, const Env& env) noexcept(see below);
+  constexpr queryable decltype(auto) default_domain::transform_env(Sndr&& sndr, Env&& env) noexcept;
 
-1. Returns: `tag_of_t().transform_sender(std::forward(sndr), env)` - if that expression is well-formed; otherwise, `std::forward(sndr)`. - -2. Remarks: The exception specification is equivalent to: +4. Let e be the expression + `tag_of_t().transform_env(std::forward(sndr), + std::forward(env))` if that expression is well-formed; otherwise, + `static_cast(std::forward(env))`. -
-    noexcept(tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr), env))
-    
+5. Mandates: noexcept(e) is `true`. - if that expression is well-formed; otherwise, `true`; +6. Returns: e.
-template <sender Sndr, queryable Env>
-  constexpr decltype(auto) default_domain::transform_env(Sndr&& sndr, Env&& env) noexcept;
+template<class Tag, sender Sndr, class... Args>
+  constexpr decltype(auto) default_domain::apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
 
-3. Returns: `tag_of_t().transform_env(std::forward(sndr), std::forward(env))` - if that expression is well-formed; otherwise, `static_cast(std::forward(env))`. +7. Let e be the expression + `Tag().apply_sender(std::forward(sndr), std::forward(args)...)` + if that expression is well-formed; otherwise, this function shall not + participate in overload resolution. + +8. Constraints: e is a well-formed expression. + +9. Returns: e. + +10. Remarks: The exception specification is equivalent to noexcept(e). -4. Mandates: The selected expression in Returns: is not potentially throwing. +### `execution::transform_sender` [exec.snd.transform] ### {#spec-execution.sender_transform}
-template<class Tag, sender Sndr, class... Args>
-  static constexpr decltype(auto) default_domain::apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+template<class Domain, sender Sndr, queryable... Env>
+    requires (sizeof...(Env) <= 1)
+  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below);
 
-5. Returns: `Tag().apply_sender(std::forward(sndr), std::forward(args)...)` - if that expression is well-formed; otherwise, this function shall not participate - in overload resolution. +1. Let sndr2 be the expression + `dom.transform_sender(std::forward(sndr), env...)` if that expression + is well-formed; otherwise, + `default_domain().transform_sender(std::forward(sndr), env...)`. Let + sndr3 be sndr2 if + sndr2 and `sndr` have the same type ignoring *cv* + qualifiers; otherwise, transform_sender(dom, sndr2, env...). -6. Remarks: The exception specification is equivalent to: +2. Returns: sndr3. -
-    noexcept(Tag().apply_sender(std::forward<Sndr>(sndr), std::forward<Args>(args)...))
-    
+3. Remarks: The exception specification is equivalent to + noexcept(sndr3). -### `execution::transform_sender` [exec.snd.transform] ### {#spec-execution.sender_transform} +### `execution::transform_env` [exec.snd.transform.env] ### {#spec-execution.env_transform}
-template<class Domain, sender Sndr>
-  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr);
-
 template<class Domain, sender Sndr, queryable Env>
-  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env& env);
+  constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
 
-1. Returns: Let ENV be a parameter pack consisting of - the single expression `env` for the second overload and an empty pack for - the first. Let `sndr2` be the expression - dom.transform_sender(std::forward<Sndr>(sndr), - ENV...) if that expression is well-formed; otherwise, - default_domain().transform_sender(std::forward<Sndr>(sndr), - ENV...). If `sndr2` and `sndr` have the same type ignoring *cv* - qualifiers, returns `sndr2`; otherwise, transform_sender(dom, sndr2, - ENV...). +1. Let e be the expression + `dom.transform_env(std::forward(sndr), std::forward(env))` if + that expression is well-formed; otherwise, + `default_domain().transform_env(std::forward(sndr), + std::forward(env))`. -
-template<class Domain, sender Sndr, queryable Env>
-  constexpr decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
-
+2. Mandates: noexcept(e) is `true`. -2. Returns: `dom.transform_env(std::forward(sndr), std::forward(env))` if that - expression is well-formed; otherwise, - `default_domain().transform_env(std::forward(sndr), std::forward(env))`. +2. Returns: e. ### `execution::apply_sender` [exec.snd.apply] ### {#spec-execution.apply_sender} @@ -5650,23 +5644,17 @@ template<class Domain, class Tag, sender Sndr, class... Args> constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
-1. Returns: `dom.apply_sender(Tag(), std::forward(sndr), std::forward(args)...)` if that - expression is well-formed; otherwise, - `default_domain().apply_sender(Tag(), std::forward(sndr), std::forward(args)...)` - if that expression is well-formed; otherwise, this function shall not participate in - overload resolution. +1. Let e be the expression `dom.apply_sender(Tag(), + std::forward(sndr), std::forward(args)...)` if that expression + is well-formed; otherwise, `default_domain().apply_sender(Tag(), + std::forward(sndr), std::forward(args)...)`. -2. Remarks: The exception specification is equivalent to: +2. Constraints: The expression e is well-formed. -
-      noexcept(dom.apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...))
-      
+1. Returns: e. - if that expression is well-formed; otherwise, - -
-      noexcept(default_domain().apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...))
-      
+2. Remarks: The exception specification is equivalent to + noexcept(e). ### `execution::get_completion_signatures` [exec.getcomplsigs] ### {#spec-execution.getcomplsigs} From 6c9ab3edebcc3286ca4e9188b5d82039e4c9607e Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 20 Mar 2024 13:01:35 -0700 Subject: [PATCH 36/89] LWG wording feedback from March 20, 2024 --- execution.bs | 47 +++++++++++++++++++++++------------------------ 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/execution.bs b/execution.bs index d12a9e8..3dbdfdb 100644 --- a/execution.bs +++ b/execution.bs @@ -4085,11 +4085,11 @@ template<class C> non-senders as arguments and that returns a sender. * A sender adaptor is a function that constructs and - returns a parent sender from a set of one or more child senders and a - (possibly empty) set of additional arguments. An asynchronous operation - created by a parent sender is a parent to the - child operations created by the child - senders. + returns a parent sender from a set of one or more + child senders and a (possibly + empty) set of additional arguments. An asynchronous operation created by + a parent sender is a parent operation to the child operations created by + the child senders. * A sender consumer is a function that takes one or more senders and a (possibly empty) set of additional arguments, and @@ -5558,7 +5558,7 @@ struct default_domain {
 template <sender Sndr, queryable... Env>
     requires (sizeof...(Env) <= 1)
-  constexpr sender decltype(auto) default_domain::transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
+  constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
 
1. Let e be the expression @@ -5571,7 +5571,7 @@ template <sender Sndr, queryable... Env>
 template <sender Sndr, queryable Env>
-  constexpr queryable decltype(auto) default_domain::transform_env(Sndr&& sndr, Env&& env) noexcept;
+  constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
 
4. Let e be the expression @@ -5585,13 +5585,11 @@ template <sender Sndr, queryable Env>
 template<class Tag, sender Sndr, class... Args>
-  constexpr decltype(auto) default_domain::apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+  constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
 
7. Let e be the expression - `Tag().apply_sender(std::forward(sndr), std::forward(args)...)` - if that expression is well-formed; otherwise, this function shall not - participate in overload resolution. + `Tag().apply_sender(std::forward(sndr), std::forward(args)...)`. 8. Constraints: e is a well-formed expression. @@ -5607,18 +5605,20 @@ template<class Domain, sender Sndr, queryable... Env> constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below);
-1. Let sndr2 be the expression +1. Let transformed-sndr be the expression `dom.transform_sender(std::forward(sndr), env...)` if that expression is well-formed; otherwise, `default_domain().transform_sender(std::forward(sndr), env...)`. Let - sndr3 be sndr2 if - sndr2 and `sndr` have the same type ignoring *cv* - qualifiers; otherwise, transform_sender(dom, sndr2, env...). + final-sndr be the expression + transformed-sndr if transformed-sndr + and `sndr` have the same type ignoring *cv* qualifiers; otherwise, it is the + expression transform_sender(dom, transformed-sndr, + env...). -2. Returns: sndr3. +2. Returns: final-sndr. 3. Remarks: The exception specification is equivalent to - noexcept(sndr3). + noexcept(final-sndr). ### `execution::transform_env` [exec.snd.transform.env] ### {#spec-execution.env_transform} @@ -5897,12 +5897,11 @@ template<class Domain, class Tag, sender Sndr, class... Args> chains. The adaptors also support function call syntax with equivalent semantics. -3. Unless otherwise specified, a sender adaptor is required to not begin - executing any functions that would observe or modify any of the arguments - of the adaptor before the returned sender is connected with a receiver using - `connect`, and `start` is called on the resulting operation state. This - requirement applies to any function that is selected by the implementation - of the sender adaptor. +3. Unless otherwise specified, a sender adaptor is prohibited from causing + observable effects, apart from moving and copying its arguments, before the + returned sender is connected with a receiver using `connect`, and `start` is + called on the resulting operation state. This requirement applies to any + function that is selected by the implementation of the sender adaptor. 4. Unless otherwise specified, a parent sender ([async.ops]) with a single child sender `sndr` has an associated attribute object equal to @@ -5915,7 +5914,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 5. Unless otherwise specified, when a parent sender is connected to a receiver `rcvr`, any receiver used to connect a child sender has an associated environment equal to FWD-ENV(get_env(rcvr)). This - requirements applies to any sender returned from a function that is selected + requirement applies to any sender returned from a function that is selected by the implementation of such sender adaptor. 6. For any sender type, receiver type, operation state type, queryable type, or From 160073921605f92674d9ef25a797ed89c92361ae Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 19 Mar 2024 16:19:03 -0700 Subject: [PATCH 37/89] remove tag_invoke --- execution.bs | 1139 ++++++++++++++++++++------------------------------ 1 file changed, 459 insertions(+), 680 deletions(-) diff --git a/execution.bs b/execution.bs index 3dbdfdb..cd1c294 100644 --- a/execution.bs +++ b/execution.bs @@ -3118,8 +3118,6 @@ Using `tag_invoke` has the following benefits: Much of this wording follows the wording of [[P0443R14]]. -[[#spec-library]] is meant to be a diff relative to the wording of the [library] clause of [[N4885]]. - [[#spec-utilities]] is meant to be a diff relative to the wording of the [utilities] clause of [[N4885]]. This diff applies changes from [[P1895R0]]. [[#spec-thread]] is meant to be a diff relative to the wording of the [thread] clause of [[N4885]]. This diff applies changes from [[P2175R0]]. @@ -3164,70 +3162,6 @@ headers [tab:headers.cpp] -
In subclause [conforming], after [lib.types.movedfrom], -add the following new subclause with suggested stable name [lib.tmpl-heads].
- - -
-**16.4.6.17 Class template-heads** - -1. If a class template's template-head is marked with "*arguments are not - associated entities*"", any template arguments do not contribute to the - associated entities ([basic.lookup.argdep]) of a function call where a - specialization of the class template is an associated entity. In such a case, - the class template can be implemented as an alias template referring to a - templated class, or as a class template where the template arguments - themselves are templated classes. - -2. [*Example:* - -
-    template<class T> // arguments are not associated entities
-    struct S {};
-
-    namespace N {
-      int f(auto);
-      struct A {};
-    }
-
-    int x = f(S<N::A>{});  // error: N::f not a candidate
-    
- - The template `S` specified above can be implemented as - -
-    template<class T>
-    struct s-impl {
-      struct type { };
-    };
-
-    template<class T>
-    using S = s-impl<T>::type;
-    
- - or as - -
-    template<class T>
-    struct hidden {
-      using type = struct _ {
-        using type = T;
-      };
-    };
-
-    template<class HiddenT>
-    struct s-impl {
-      using T = HiddenT::type;
-    };
-
-    template<class T>
-    using S = s-impl<typename hidden<T>::type>;
-    
- - -- end example] -
-
- # General utilities library [utilities] # {#spec-utilities} ## Function objects [function.objects] ## {#spec-function.objects} @@ -3239,88 +3173,27 @@ At the end of this subclause, insert the following declarations into the synopsi
-// expositon only:
 template<class Fn, class... Args>
-  concept callable =
+  concept callable =  // expositon only
     requires (Fn&& fn, Args&&... args) {
       std::forward<Fn>(fn)(std::forward<Args>(args)...);
     };
 template<class Fn, class... Args>
-  concept nothrow-callable =
+  concept nothrow-callable =   // expositon only
     callable<Fn, Args...> &&
     requires (Fn&& fn, Args&&... args) {
       { std::forward<Fn>(fn)(std::forward<Args>(args)...) } noexcept;
     };
+// expositon only:
 template<class Fn, class... Args>
   using call-result-t = decltype(declval<Fn>()(declval<Args>()...));
 
-// [func.tag_invoke], tag_invoke
-namespace tag-invoke { // exposition only
-  void tag_invoke();
-
-  template<class Tag, class... Args>
-    concept tag_invocable =
-      requires (Tag&& tag, Args&&... args) {
-        tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...);
-      };
-
-  template<class Tag, class... Args>
-    concept nothrow_tag_invocable =
-      tag_invocable<Tag, Args...> &&
-      requires (Tag&& tag, Args&&... args) {
-        { tag_invoke(std::forward<Tag>(tag), std::forward<Args>(args)...) } noexcept;
-      };
-
-  template<class Tag, class... Args>
-    using tag_invoke_result_t =
-      decltype(tag_invoke(declval<Tag>(), declval<Args>()...));
-
-  template<class Tag, class... Args>
-    struct tag_invoke_result<Tag, Args...> {
-      using type =
-        tag_invoke_result_t<Tag, Args...>; // present if and only if tag_invocable<Tag, Args...> is true
-    };
-
-  struct tag; // exposition only
-}
-inline constexpr tag-invoke::tag tag_invoke {};
-using tag-invoke::tag_invocable;
-using tag-invoke::nothrow_tag_invocable;
-using tag-invoke::tag_invoke_result_t;
-using tag-invoke::tag_invoke_result;
-
 template<auto& Tag>
   using tag_t = decltype(auto(Tag));
 
-### `tag_invoke` [func.tag_invoke] ### {#spec-func.tag_invoke} - -Insert this subclause as a new subclause, between Searchers [func.search] and Class template `hash` [unord.hash]. - - -
- -1. Given a subexpression `E`, let REIFY(E) be expression-equivalent to - a glvalue with the same type and value as `E` as if by `identity()(E)`. - -2. The name `std::tag_invoke` denotes a customization point object [customization.point.object]. - Given subexpressions `T` and `A...`, the expression `std::tag_invoke(T, A...)` is - expression-equivalent [defns.expression-equivalent] to - tag_invoke(REIFY(T), REIFY(A)...) - with overload resolution performed in a context in which unqualified lookup for `tag_invoke` - finds only the declaration - - ```c++ - void tag_invoke(); - ``` - -2. [Note: Diagnosable ill-formed cases above result in substitution failure when `std::tag_invoke(T, A...)` appears in the immediate context of a template instantiation. —end note] - -
-
- # Thread support library [thread] # {#spec-thread} ## Stop tokens [thread.stoptoken] ## {#spec-thread.stoptoken} @@ -3832,16 +3705,12 @@ template<class C> 4. This clause makes use of the following exposition-only entities: - 1.
-        template<class Fn, class... Args>
-            requires callable<Fn, Args...>
-          constexpr auto mandate-nothrow-call(Fn&& fn, Args&&... args) noexcept
-            -> call-result-t<Fn, Args...> {
-            return std::forward<Fn>(fn)(std::forward<Args>(args)...);
-          }
-        
- - * Mandates: nothrow-callable<Fn, Args...> is `true`. + 1. For a subexpression expr, let + MANDATE-NOTHROW(expr) + be expression-equivalent to expr. + + * Mandates: noexcept(expr) is + true. 2.
         template<class T>
@@ -3892,9 +3761,8 @@ template<class C>
     ([concepts.equality]) and does not modify the function object or the
     arguments.
 
-5. If tag_invoke(q, env, args...) is well-formed, then
-    q(env, args...) is expression-equivalent to
-    tag_invoke(q, env, args...).
+5. If the expression env.query(q, args...) is well-formed,
+    then it is expression-equivalent to q(env, args...).
 
 6. Unless otherwise specified, the value returned by the expression
     q(env, args...) is valid as long as `env` is valid.
@@ -4111,17 +3979,13 @@ namespace std {
 
   // [exec.queryable], queryable objects
   template<class T>
-    concept queryable = destructible;
+    concept queryable = destructible<T>;
 
   // [exec.queries], queries
-  namespace queries { // exposition only
-    struct forwarding_query_t;
-    struct get_allocator_t;
-    struct get_stop_token_t;
-  }
-  using queries::forwarding_query_t;
-  using queries::get_allocator_t;
-  using queries::get_stop_token_t;
+  struct forwarding_query_t;
+  struct get_allocator_t;
+  struct get_stop_token_t;
+
   inline constexpr forwarding_query_t forwarding_query{};
   inline constexpr get_allocator_t get_allocator{};
   inline constexpr get_stop_token_t get_stop_token{};
@@ -4138,19 +4002,13 @@ namespace std {
 namespace std::execution {
   // [exec.queries], queries
   enum class forward_progress_guarantee;
-  namespace queries { // exposition only
-    struct get_domain_t;
-    struct get_scheduler_t;
-    struct get_delegatee_scheduler_t;
-    struct get_forward_progress_guarantee_t;
-    template<class CPO>
-      struct get_completion_scheduler_t;
-  }
-  using queries::get_domain_t;
-  using queries::get_scheduler_t;
-  using queries::get_delegatee_scheduler_t;
-  using queries::get_forward_progress_guarantee_t;
-  using queries::get_completion_scheduler_t;
+  struct get_domain_t;
+  struct get_scheduler_t;
+  struct get_delegatee_scheduler_t;
+  struct get_forward_progress_guarantee_t;
+  template<class CPO>
+    struct get_completion_scheduler_t;
+
   inline constexpr get_domain_t get_domain{};
   inline constexpr get_scheduler_t get_scheduler{};
   inline constexpr get_delegatee_scheduler_t get_delegatee_scheduler{};
@@ -4158,12 +4016,8 @@ namespace std::execution {
   template<class CPO>
     inline constexpr get_completion_scheduler_t<CPO> get_completion_scheduler{};
 
-  namespace exec-envs { // exposition only
-    struct empty_env {};
-    struct get_env_t;
-  }
-  using envs-envs::empty_env;
-  using envs-envs::get_env_t;
+  struct empty_env {};
+  struct get_env_t;
   inline constexpr get_env_t get_env {};
 
   template<class T>
@@ -4173,29 +4027,24 @@ namespace std::execution {
   struct default_domain;
 
   // [exec.sched], schedulers
+  struct scheduler_t {};
+
   template<class Sch>
     concept scheduler = see below;
 
   // [exec.recv], receivers
   struct receiver_t {};
 
-  template<class Rcvr>
-    inline constexpr bool enable_receiver = see below;
-
   template<class Rcvr>
     concept receiver = see below;
 
   template<class Rcvr, class Completions>
     concept receiver_of = see below;
 
-  namespace receivers { // exposition only
-    struct set_value_t;
-    struct set_error_t;
-    struct set_stopped_t;
-  }
-  using receivers::set_value_t;
-  using receivers::set_error_t;
-  using receivers::set_stopped_t;
+  struct set_value_t;
+  struct set_error_t;
+  struct set_stopped_t;
+
   inline constexpr set_value_t set_value{};
   inline constexpr set_error_t set_error{};
   inline constexpr set_stopped_t set_stopped{};
@@ -4204,18 +4053,12 @@ namespace std::execution {
   template<class O>
     concept operation_state = see below;
 
-  namespace op-state { // exposition only
-    struct start_t;
-  }
-  using op-state::start_t;
+  struct start_t;
   inline constexpr start_t start{};
 
   // [exec.snd], senders
   struct sender_t {};
 
-  template<class Sndr>
-    inline constexpr bool enable_sender = see below;
-
   template<class Sndr>
     concept sender = see below;
 
@@ -4235,10 +4078,7 @@ namespace std::execution {
     concept single-sender = see below; // exposition only
 
   // [exec.getcomplsigs], completion signatures
-  namespace completion-signatures { // exposition only
-    struct get_completion_signatures_t;
-  }
-  using completion-signatures::get_completion_signatures_t;
+  struct get_completion_signatures_t;
   inline constexpr get_completion_signatures_t get_completion_signatures {};
 
   template<class Sndr, class Env = empty_env>
@@ -4272,40 +4112,34 @@ namespace std::execution {
     using tag_of_t = see below;
 
   // [exec.snd.transform], sender transformations
-  template<class Domain, sender Sndr>
-    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndrv);
-
-  template<class Domain, sender Sndr, queryable Env>
-    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env& env);
+  template<class Domain, sender Sndr, queryable... Env>
+      requires (sizeof...(Env) <= 1)
+    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below);
 
+  // [exec.snd.transform.env], environment transformations
   template<class Domain, sender Sndr, queryable Env>
-    constexpr decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+    constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
 
   // [exec.snd.apply], sender algorithm application
   template<class Domain, class Tag, sender Sndr, class... Args>
     constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
 
   // [exec.connect], the connect sender algorithm
-  namespace senders-connect { // exposition only
-    struct connect_t;
-  }
-  using senders-connect::connect_t;
+  struct connect_t;
   inline constexpr connect_t connect{};
 
   template<class Sndr, class Rcvr>
     using connect_result_t = decltype(connect(declval<Sndr>(), declval<Rcvr>()));
 
   // [exec.factories], sender factories
-  namespace sender-factories { // exposition only
-    struct just_t;
-    struct just_error_t;
-    struct just_stopped_t;
-    struct schedule_t;
-  }
-  inline constexpr just just{};
+  struct just_t;
+  struct just_error_t;
+  struct just_stopped_t;
+  struct schedule_t;
+
+  inline constexpr just_t just{};
   inline constexpr just_error_t just_error{};
   inline constexpr just_stopped_t just_stopped{};
-  using sender-factories::schedule_t;
   inline constexpr schedule_t schedule{};
   inline constexpr unspecified read{};
 
@@ -4313,109 +4147,66 @@ namespace std::execution {
     using schedule_result_t = decltype(schedule(declval<Sndr>()));
 
   // [exec.adapt], sender adaptors
-  namespace sender-adaptor-closure { // exposition only
-    template<class-type D>
-      struct sender_adaptor_closure { };
-  }
-  using sender-adaptor-closure::sender_adaptor_closure;
-
-  namespace sender-adaptors { // exposition only
-    struct on_t;
-    struct transfer_t;
-    struct schedule_from_t;
-    struct then_t;
-    struct upon_error_t;
-    struct upon_stopped_t;
-    struct let_value_t;
-    struct let_error_t;
-    struct let_stopped_t;
-    struct bulk_t;
-    struct split_t;
-    struct when_all_t;
-    struct when_all_with_variant_t;
-    struct into_variant_t;
-    struct stopped_as_optional_t;
-    struct stopped_as_error_t;
-    struct ensure_started_t;
-  }
-  using sender-adaptors::on_t;
-  using sender-adaptors::transfer_t;
-  using sender-adaptors::schedule_from_t;
-  using sender-adaptors::then_t;
-  using sender-adaptors::upon_error_t;
-  using sender-adaptors::upon_stopped_t;
-  using sender-adaptors::let_value_t;
-  using sender-adaptors::let_error_t;
-  using sender-adaptors::let_stopped_t;
-  using sender-adaptors::bulk_t;
-  using sender-adaptors::split_t;
-  using sender-adaptors::when_all_t;
-  using sender-adaptors::when_all_with_variant_t;
-  using sender-adaptors::into_variant_t;
-  using sender-adaptors::stopped_as_optional_t;
-  using sender-adaptors::stopped_as_error_t;
-  using sender-adaptors::ensure_started_t;
+  template<class-type D>
+    struct sender_adaptor_closure { };
+
+  struct on_t;
+  struct transfer_t;
+  struct schedule_from_t;
+  struct then_t;
+  struct upon_error_t;
+  struct upon_stopped_t;
+  struct let_value_t;
+  struct let_error_t;
+  struct let_stopped_t;
+  struct bulk_t;
+  struct split_t;
+  struct ensure_started_t;
+  struct when_all_t;
+  struct when_all_with_variant_t;
+  struct into_variant_t;
+  struct stopped_as_optional_t;
+  struct stopped_as_error_t;
 
   inline constexpr on_t on{};
   inline constexpr transfer_t transfer{};
   inline constexpr schedule_from_t schedule_from{};
-
   inline constexpr then_t then{};
   inline constexpr upon_error_t upon_error{};
   inline constexpr upon_stopped_t upon_stopped{};
-
   inline constexpr let_value_t let_value{};
   inline constexpr let_error_t let_error{};
   inline constexpr let_stopped_t let_stopped{};
-
   inline constexpr bulk_t bulk{};
-
   inline constexpr split_t split{};
+  inline constexpr ensure_started_t ensure_started{};
   inline constexpr when_all_t when_all{};
   inline constexpr when_all_with_variant_t when_all_with_variant{};
-
   inline constexpr into_variant_t into_variant{};
-
   inline constexpr stopped_as_optional_t stopped_as_optional;
-
   inline constexpr stopped_as_error_t stopped_as_error;
 
-  inline constexpr ensure_started_t ensure_started{};
-
   // [exec.consumers], sender consumers
-  namespace sender-consumers { // exposition only
-    struct start_detached_t;
-  }
-  using sender-consumers::start_detached_t;
+  struct start_detached_t;
   inline constexpr start_detached_t start_detached{};
 
   // [exec.utils], sender and receiver utilities
   // [exec.utils.rcvr.adptr]
-  template<
-      class-type Derived,
-      receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
+  template<class-type Derived, receiver Base = unspecified>
     class receiver_adaptor;
 
+  // [exec.utils.cmplsigs]
   template<class Fn>
     concept completion-signature = // exposition only
       see below;
 
-  // [exec.utils.cmplsigs]
   template<completion-signature... Fns>
     struct completion_signatures {};
 
-  template<class... Args> // exposition only
-    using default-set-value =
-      completion_signatures<set_value_t(Args...)>;
-
-  template<class Err> // exposition only
-    using default-set-error =
-      completion_signatures<set_error_t(Err)>;
-
   template<class Sigs> // exposition only
     concept valid-completion-signatures = see below;
 
-  // [exec.utils.mkcmplsigs]
+  // [exec.utils.tfxcmplsigs]
   template<
     valid-completion-signatures InputSignatures,
     valid-completion-signatures AdditionalSignatures = completion_signatures<>,
@@ -4437,47 +4228,29 @@ namespace std::execution {
       completion_signatures_of_t<Sndr, Env>, AdditionalSignatures, SetValue, SetError, SetStopped>;
 
   // [exec.ctx], execution resources
+  // [exec.run.loop], run_loop
   class run_loop;
 }
 
 namespace std::this_thread {
   // [exec.queries], queries
-  namespace queries { // exposition only
-    struct execute_may_block_caller_t;
-  }
-  using queries::execute_may_block_caller_t;
+  struct execute_may_block_caller_t;
   inline constexpr execute_may_block_caller_t execute_may_block_caller{};
 
-  namespace this-thread { // exposition only
-    struct sync-wait-env; // exposition only
-    template<class Sndr>
-        requires sender_in<Sndr, sync-wait-env>
-      using sync-wait-result-type = see below; // exposition only
-    template<class Sndr>
-      using sync-wait-with-variant-result-type = see below; // exposition only
+  struct sync_wait_t;
+  struct sync_wait_with_variant_t;
 
-    struct sync_wait_t;
-    struct sync_wait_with_variant_t;
-  }
-  using this-thread::sync_wait_t;
-  using this-thread::sync_wait_with_variant_t;
   inline constexpr sync_wait_t sync_wait{};
   inline constexpr sync_wait_with_variant_t sync_wait_with_variant{};
 }
 
 namespace std::execution {
   // [exec.execute], one-way execution
-  namespace execute { // exposition only
-    struct execute_t;
-  }
-  using execute::execute_t;
+  struct execute_t;
   inline constexpr execute_t execute{};
 
   // [exec.as.awaitable]
-  namespace coro-utils { // exposition only
-    struct as_awaitable_t;
-  }
-  using coro-utils::as_awaitable_t;
+  struct as_awaitable_t;
   inline constexpr as_awaitable_t as_awaitable;
 
   // [exec.with.awaitable.senders]
@@ -4514,8 +4287,8 @@ namespace std::execution {
     object `q` of type `Q`, `forwarding_query(q)` is expression-equivalent
     to:
 
-    1. mandate-nothrow-call(tag_invoke, forwarding_query,
-        q) if that expression is well-formed.
+    1. MANDATE-NOTHROW(q.query(forwarding_query)) if that
+        expression is well-formed.
 
         * Mandates: The expression above has type `bool` and is a core
             constant expressions if `q` is a core constant expression.
@@ -4529,15 +4302,15 @@ namespace std::execution {
 
 1. `get_allocator` asks an object for its associated allocator.
 
-2. The name `get_allocator` denotes a query object. For some subexpression `env`,
+2. The name `get_allocator` denotes a query object. For a subexpression `env`,
     `get_allocator(env)` is expression-equivalent to
-    mandate-nothrow-call(tag_invoke, get_allocator,
-    as_const(env)).
+    MANDATE-NOTHROW(as_const(env).query(get_allocator)).
 
-        * Mandates: The type of the expression above
-            satisfies Allocator.
+      * Mandates: If the expression above is well-formed, its type
+          satisfies Allocator.
 
-3. `forwarding_query(get_allocator)` is `true`.
+3. `forwarding_query(get_allocator)` is a core constant
+    expression and has value `true`.
 
 4. `get_allocator()` (with no arguments) is expression-equivalent to
     `execution::read(get_allocator)` ([exec.read]).
@@ -4546,11 +4319,11 @@ namespace std::execution {
 
 1. `get_stop_token` asks an object for an associated stop token.
 
-2. The name `get_stop_token` denotes a query object. For some subexpression `env`,
+2. The name `get_stop_token` denotes a query object. For a subexpression `env`,
     `get_stop_token(env)` is expression-equivalent to:
 
-    1. mandate-nothrow-call(tag_invoke, get_stop_token,
-        as_const(env)), if this expression is well-formed.
+    1. MANDATE-NOTHROW(as_const(env).query(get_stop_token))
+        if that expression is well-formed.
 
         * Mandates: The type of the expression above satisfies
             `stoppable_token`.
@@ -4565,10 +4338,10 @@ namespace std::execution {
 
 ### `execution::get_env` [exec.get.env] ### {#spec-execution.environment.get_env}
 
-1. `get_env` is a customization point object. For some subexpression `o` of type
-    `O`, `get_env(o)` is expression-equivalent to
+1. `execution::get_env` is a customization point object. For a subexpression
+    `o`, `execution::get_env(o)` is expression-equivalent to:
 
-    1. `tag_invoke(get_env, const_cast(o))` if that expression is
+    1. `as_const(o).get_env()` if that expression is
         well-formed.
 
         * Mandates: The expression above is not potentially throwing, and
@@ -4578,17 +4351,17 @@ namespace std::execution {
 
 2. The value of `get_env(o)` shall be valid while `o` is valid.
 
-3. When passed a sender object, `get_env` returns the sender's attributes. When
-    passed a receiver, `get_env` returns the receiver's environment.
+3. When passed a sender object, `get_env` returns the
+    sender's attributes. When passed a receiver, `get_env` returns the
+    receiver's environment.
 
 ### `execution::get_domain` [exec.get.domain] ### {#spec-execution.get_domain}
 
 1. `get_domain` asks an object for an associated execution domain tag.
 
-2. The name `get_domain` denotes a query object. For some subexpression `env`,
+2. The name `get_domain` denotes a query object. For a subexpression `env`,
     `get_domain(env)` is expression-equivalent to
-    mandate-nothrow-call(tag_invoke, get_domain, as_const(env)),
-    if this expression is well-formed.
+    MANDATE-NOTHROW(as_const(env).query(get_domain)).
 
 3. `forwarding_query(execution::get_domain)` is a core constant
     expression and has value `true`.
@@ -4600,31 +4373,36 @@ namespace std::execution {
 
 1. `get_scheduler` asks an object for its associated scheduler.
 
-2. The name `get_scheduler` denotes a query object. For some
+2. The name `get_scheduler` denotes a query object. For a
     subexpression `env`,  `get_scheduler(env)` is expression-equivalent to
-    mandate-nothrow-call(tag_invoke, get_scheduler, as_const(env)).
+    MANDATE-NOTHROW(as_const(env).query(get_scheduler)).
 
-        * Mandates: The type of the expression above satisfies `scheduler`.
+      * Mandates: If the expression above is well-formed, its type
+          satisfies `scheduler`.
 
 3. `forwarding_query(execution::get_scheduler)` is a core constant
     expression and has value `true`.
 
-4. `get_scheduler()` (with no arguments) is expression-equivalent to `execution::read(get_scheduler)` ([exec.read]).
+4. `get_scheduler()` (with no arguments) is expression-equivalent to
+    `execution::read(get_scheduler)` ([exec.read]).
 
 ### `execution::get_delegatee_scheduler` [exec.get.delegatee.scheduler] ### {#spec-execution.get_delegatee_scheduler}
 
-1. `get_delegatee_scheduler` asks an object for a scheduler that can be used to delegate work to for the purpose of forward progress delegation.
+1. `get_delegatee_scheduler` asks an object for a scheduler that can be used to
+    delegate work to for the purpose of forward progress delegation.
 
-2. The name `get_delegatee_scheduler` denotes a query object. For some
+2. The name `get_delegatee_scheduler` denotes a query object. For a
     subexpression `env`, `get_delegatee_scheduler(env)` is expression-equivalent to
-    mandate-nothrow-call(tag_invoke, get_delegatee_scheduler, as_const(env)).
+    MANDATE-NOTHROW(as_const(env).query(get_delegatee_scheduler)).
 
-        * Mandates: The type of the expression above is satisfies `scheduler`.
+      * Mandates: If the expression above is well-formed, its type
+          satisfies `scheduler`.
 
 3. `forwarding_query(execution::get_delegatee_scheduler)` is a core
     constant expression and has value `true`.
 
-4. `get_delegatee_scheduler()` (with no arguments) is expression-equivalent to `execution::read(get_delegatee_scheduler)`  ([exec.read]).
+4. `get_delegatee_scheduler()` (with no arguments) is expression-equivalent to
+    `execution::read(get_delegatee_scheduler)` ([exec.read]).
 
 ### `execution::get_forward_progress_guarantee` [exec.get.forward.progress.guarantee] ### {#spec-execution.get_forward_progress_guarantee}
 
@@ -4636,35 +4414,52 @@ enum class forward_progress_guarantee {
 };
 
-1. `get_forward_progress_guarantee` asks a scheduler about the forward progress guarantees of execution agents created by that scheduler. +1. `get_forward_progress_guarantee` asks a scheduler about the forward progress + guarantee of execution agents created by that scheduler. -2. The name `get_forward_progress_guarantee` denotes a query object. For some subexpression `sch`, let `Sch` be `decltype((sch))`. If `Sch` does not satisfy `scheduler`, `get_forward_progress_guarantee` is ill-formed. - Otherwise, `get_forward_progress_guarantee(sch)` is expression-equivalent to: +2. The name `get_forward_progress_guarantee` denotes a query object. For a + subexpression `sch`, let `Sch` be `decltype((sch))`. If `Sch` does not + satisfy `scheduler`, `get_forward_progress_guarantee` is ill-formed. + Otherwise, `get_forward_progress_guarantee(sch)` is expression-equivalent + to: - 1. mandate-nothrow-call(tag_invoke, get_forward_progress_guarantee, as_const(sch)), if this expression is well-formed. + 1. MANDATE-NOTHROW(as_const(sch).query(get_forward_progress_guarantee)), + if this expression is well-formed. * Mandates: The type of the expression above is `forward_progress_guarantee`. 2. Otherwise, `forward_progress_guarantee::weakly_parallel`. -3. If `get_forward_progress_guarantee(sch)` for some scheduler `sch` returns `forward_progress_guarantee::concurrent`, all execution agents created by that scheduler shall provide the concurrent forward progress guarantee. If it returns - `forward_progress_guarantee::parallel`, all execution agents created by that scheduler shall provide at least the parallel forward progress guarantee. +3. If `get_forward_progress_guarantee(sch)` for some scheduler `sch` returns + `forward_progress_guarantee::concurrent`, all execution agents created by + that scheduler shall provide the concurrent forward progress guarantee. If + it returns `forward_progress_guarantee::parallel`, all execution agents + created by that scheduler shall provide at least the parallel forward + progress guarantee. ### `this_thread::execute_may_block_caller` [exec.execute.may.block.caller] ### {#spec-execution.execute_may_block_caller} -1. `this_thread::execute_may_block_caller` asks a scheduler `sch` whether a call `execute(sch, f)` with any invocable `f` may block the thread where such a call occurs. +1. `this_thread::execute_may_block_caller` asks a scheduler `sch` whether a call + `execute(sch, f)` with any invocable `f` may block the thread where such a + call occurs. -2. The name `this_thread::execute_may_block_caller` denotes a query object. For some subexpression `sch`, let `Sch` be `decltype((sch))`. If `Sch` does not satisfy `scheduler`, `this_thread::execute_may_block_caller` is ill-formed. Otherwise, - `this_thread::execute_may_block_caller(sch)` is expression-equivalent to: +2. The name `this_thread::execute_may_block_caller` denotes a query object. For + a subexpression `sch`, let `Sch` be `decltype((sch))`. If `Sch` does not + satisfy `scheduler`, `this_thread::execute_may_block_caller` is ill-formed. + Otherwise, `this_thread::execute_may_block_caller(sch)` is + expression-equivalent to: - 1. mandate-nothrow-call(tag_invoke, this_thread::execute_may_block_caller, as_const(sch)), if this expression is well-formed. + 1. MANDATE-NOTHROW(as_const(sch).query(this_thread::execute_may_block_caller)), + if this expression is well-formed. * Mandates: The type of the expression above is `bool`. 2. Otherwise, `true`. -3. If `this_thread::execute_may_block_caller(sch)` for some scheduler `sch` returns `false`, no `execute(sch, f)` call with some invocable `f` shall block the calling thread. +3. If `this_thread::execute_may_block_caller(sch)` for some scheduler `sch` + returns `false`, no `execute(sch, f)` call with some invocable `f` shall + block the calling thread. ### `execution::get_completion_scheduler` [exec.completion.scheduler] ### {#spec-execution.get_completion_scheduler} @@ -4672,17 +4467,16 @@ enum class forward_progress_guarantee { completion scheduler associated with a completion tag from a sender's attributes. -2. The name `get_completion_scheduler` denotes a query object template. For some +2. The name `get_completion_scheduler` denotes a query object template. For a subexpression `q`, let `Q` be `decltype((q))`. If the template argument `Tag` in `get_completion_scheduler(q)` is not one of `set_value_t`, `set_error_t`, or `set_stopped_t`, `get_completion_scheduler(q)` is ill-formed. Otherwise, `get_completion_scheduler(q)` is - expression-equivalent to mandate-nothrow-call(tag_invoke, - get_completion_scheduler<Tag>, as_const(q)) if this expression is - well-formed. + expression-equivalent to + MANDATE-NOTHROW(as_const(q).query(get_completion_scheduler<Tag>)). - * Mandates: The type of the expression above satisfies - `scheduler`. + * Mandates: If the expression above is well-formed, its type + satisfies `scheduler`. 3. If, for some sender `sndr` and completion function `C` that has an associated completion tag `Tag`, `get_completion_scheduler(get_env(sndr))` is @@ -4702,13 +4496,20 @@ enum class forward_progress_guarantee { scheduler. A valid invocation of `schedule` is a schedule-expression.
+    template<class Sch>
+      concept enable-scheduler = // exposition only
+        requires {
+          requires derived_from<typename Sch::scheduler_concept, scheduler_t>;
+        };
+
     template<class Sch>
       concept scheduler =
+        enable-scheduler<remove_cvref_t<Sch>> &&
         queryable<Sch> &&
-        requires(Sch&& sch, const get_completion_scheduler_t<set_value_t> tag) {
+        requires(Sch&& sch) {
           { schedule(std::forward<Sch>(sch)) } -> sender;
-          { tag_invoke(tag, get_env(
-              schedule(std::forward<Sch>(sch)))) } -> same_as<remove_cvref_t<Sch>>;
+          { get_completion_scheduler<set_value_t>(
+              get_env(schedule(std::forward<Sch>(sch)))) } -> same_as<remove_cvref_t<Sch>>;
         } &&
         equality_comparable<remove_cvref_t<Sch>> &&
         copy_constructible<remove_cvref_t<Sch>>;
@@ -4756,15 +4557,14 @@ enum class forward_progress_guarantee {
 
     
     template<class Rcvr>
-      concept is-receiver = // exposition only
-        derived_from<typename Rcvr::receiver_concept, receiver_t>;
-
-    template<class Rcvr>
-      inline constexpr bool enable_receiver = is-receiver<Rcvr>;
+      concept enable-receiver = // exposition only
+        requires {
+          requires derived_from<typename Rcvr::receiver_concept, receiver_t>;
+        };
 
     template<class Rcvr>
       concept receiver =
-        enable_receiver<remove_cvref_t<Rcvr>> &&
+        enable-receiver<remove_cvref_t<Rcvr>> &&
         requires(const remove_cvref_t<Rcvr>& rcvr) {
           { get_env(rcvr) } -> queryable;
         } &&
@@ -4788,12 +4588,7 @@ enum class forward_progress_guarantee {
         };
     
-3. Remarks: Pursuant to [namespace.std], users can specialize `enable_receiver` to - `true` for cv-unqualified program-defined types that model `receiver`, and `false` - for types that do not. Such specializations shall be usable in constant - expressions ([expr.const]) and have type `const bool`. - -4. Let `rcvr` be a receiver and let `op_state` be an operation state associated +3. Let `rcvr` be a receiver and let `op_state` be an operation state associated with an asynchronous operation created by connecting `rcvr` with a sender. Let `token` be a stop token equal to `get_stop_token(get_env(rcvr))`. `token` shall remain valid for the duration of the asynchronous operation's lifetime @@ -4807,25 +4602,23 @@ enum class forward_progress_guarantee { 1. `set_value` is a value completion function ([async.ops]). Its associated completion tag is `set_value_t`. The expression `set_value(rcvr, vs...)` for - some subexpression `rcvr` and pack of subexpressions `vs` is ill-formed if `rcvr` + a subexpression `rcvr` and pack of subexpressions `vs` is ill-formed if `rcvr` is an lvalue or a `const` rvalue. Otherwise, it is expression-equivalent to - mandate-nothrow-call(tag_invoke, set_value, rcvr, vs...). + MANDATE-NOTHROW(rcvr.set_value(vs...)). ### `execution::set_error` [exec.set.error] ### {#spec-execution.receivers.set_error} 1. `set_error` is an error completion function. Its associated completion tag is `set_error_t`. The expression `set_error(rcvr, err)` for some subexpressions `rcvr` and `err` is ill-formed if `rcvr` is an lvalue or a `const` rvalue. Otherwise, it is - expression-equivalent to mandate-nothrow-call(tag_invoke, - set_error, rcvr, err). + expression-equivalent to MANDATE-NOTHROW(rcvr.set_error(err)). ### `execution::set_stopped` [exec.set.stopped] ### {#spec-execution.receivers.set_stopped} 1. `set_stopped` is a stopped completion function. Its associated completion tag - is `set_stopped_t`. The expression `set_stopped(rcvr)` for some subexpression + is `set_stopped_t`. The expression `set_stopped(rcvr)` for a subexpression `rcvr` is ill-formed if `rcvr` is an lvalue or a `const` rvalue. Otherwise, it is - expression-equivalent to mandate-nothrow-call(tag_invoke, - set_stopped, rcvr). + expression-equivalent to MANDATE-NOTHROW(rcvr.set_stopped()). ## Operation states [exec.opstate] ## {#spec-execution.opstate} @@ -4851,16 +4644,15 @@ enum class forward_progress_guarantee { 1. The name `start` denotes a customization point object that starts ([async.ops]) the asynchronous operation associated with the operation state - object. The expression `start(O)` for some subexpression `O` is ill-formed - if `O` is an rvalue. Otherwise, it is expression-equivalent to: + object. For a subexpression `op`, the expression `start(op)` is ill-formed + if `op` is an rvalue. Otherwise, it is expression-equivalent to:
-    mandate-nothrow-call(tag_invoke, start, O)
+    MANDATE-NOTHROW(op.start())
     
-2. If the function selected by `tag_invoke` does not start the asynchronous - operation associated with the operation state `O`, the behavior of calling - `start(O)` is undefined. +2. If `op.start()` does not start the asynchronous operation associated with the + operation state `op`, the behavior of calling `start(op)` is undefined. ## Senders [exec.snd] ## {#spec-execution.senders} @@ -4893,28 +4685,28 @@ enum class forward_progress_guarantee { 1. For a queryable object `env`, let FWD-ENV(env) be a queryable object such that for a query object `q` and a pack of - subexpressions `as`, the expression tag_invoke(q, - FWD-ENV(env), as...) is ill-formed if + subexpressions `as`, the expression + FWD-ENV(env).query(q, as...) is ill-formed if `forwarding_query(q)` is `false`; - otherwise, it is expression-equivalent to `tag_invoke(q, env, as...)`. + otherwise, it is expression-equivalent to `env.query(q, as...)`. 2. For a query object `q` and a subexpression `v`, let MAKE-ENV(q, v) be a queryable object `env` such that - the result of `tag_invoke(q, env)` has a value equal to `v` + the result of `env.query(q)` has a value equal to `v` ([concepts.equality]). Unless otherwise stated, the object to which - `tag_invoke(q, env)` refers remains valid while `env` remains valid. + `env.query(q)` refers remains valid while `env` remains valid. 3. For two queryable objects `env1` and `env2`, a query object `q` and a pack of subexpressions `as`, let JOIN-ENV(env1, - env2) be a queryable object `env3` such that `tag_invoke(q, env3, - as...)` is expression-equivalent to: + env2) be a queryable object `env3` such that + `env3.query(q, as...)` is expression-equivalent to: - - `tag_invoke(q, env1, as...)` if that expression is well-formed, + - `env1.query(q, as...)` if that expression is well-formed, - - otherwise, `tag_invoke(q, env2, as...)` if that expression is + - otherwise, `env2.query(q, as...)` if that expression is well-formed, - - otherwise, `tag_invoke(q, env3, as...)` is ill-formed. + - otherwise, `env3.query(q, as...)` is ill-formed. 4. The expansions of `FWD-ENV`, `MAKE-ENV`, and `JOIN-ENV` can be context-dependent; *i.e.*, they can expand to @@ -4923,15 +4715,15 @@ enum class forward_progress_guarantee { 5. For a scheduler `sch`, let SCHED-ATTRS(sch) be a queryable object `o1` such that - tag_invoke(get_completion_scheduler<Tag>, o1) is a + o1.query(get_completion_scheduler<Tag>) is a prvalue with the same type and value as `sch` where `Tag` is one of `set_value_t` or `set_stopped_t`; and let - tag_invoke(get_domain, o1) be expression-equivalent to - tag_invoke(get_domain, sch). Let + o1.query(get_domain) be expression-equivalent to + sch.query(get_domain). Let SCHED-ENV(sch) be a queryable object `o2` such that - tag_invoke(get_scheduler, o2) is a prvalue with the same - type and value as `sch`, and let tag_invoke(get_domain, o2) - be expression-equivalent to tag_invoke(get_domain, sch). + o1.query(get_scheduler) is a prvalue with the same + type and value as `sch`, and let o2.query(get_domain) + be expression-equivalent to sch.query(get_domain). 6. For two subexpressions `rcvr` and `expr`, let SET-VALUE(rcvr, expr) be `(expr, set_value(rcvr))` if the type of `expr` is `void`; @@ -4953,7 +4745,7 @@ enum class forward_progress_guarantee { 7.
         template<class Default = default_domain, class Sndr>
-        constexpr auto completion-domain(const Sndr& sndr) noexcept;
+          constexpr auto completion-domain(const Sndr& sndr) noexcept;
         
1. *Effects:* Let COMPL-DOMAIN(T) be the type of the expression @@ -4971,25 +4763,21 @@ enum class forward_progress_guarantee { 8.
         template<class Tag, class Env, class Default>
-        constexpr decltype(auto) query-with-default(Tag, const Env& env, Default&& value) noexcept(see below);
+          constexpr decltype(auto) query-with-default(Tag, const Env& env, Default&& value) noexcept(see below);
         
- 1. Effects: Equivalent to: - - - `return Tag()(env);` if that expression is well-formed, - - - `return static_cast(std::forward(value));` otherwise. + 1. Let e be the expression `Tag()(env)` if that + expression is well-formed; otherwise, it is + `static_cast(std::forward(value))`. - 2. Remarks: The expression in the `noexcept` clause is: + 2. Returns: e. -
-                is_invocable_v<Tag, const Env&> ? is_nothrow_invocable_v<Tag, const Env&>
-                                                : is_nothrow_constructible_v<Default, Default>
-                
+ 3. Remarks: The expression in the `noexcept` clause is + noexcept(e). 9.
         template<class Sndr>
-        constexpr auto get-domain-early(const Sndr& sndr) noexcept;
+          constexpr auto get-domain-early(const Sndr& sndr) noexcept;
         
1. Effects: Equivalent to return Domain(); @@ -5004,7 +4792,7 @@ enum class forward_progress_guarantee { 10.
         template<class Sndr, class Env>
-        constexpr auto get-domain-late(const Sndr& sndr, const Env& env) noexcept;
+          constexpr auto get-domain-late(const Sndr& sndr, const Env& env) noexcept;
         
1. Effects: Equivalent to: @@ -5059,15 +4847,15 @@ enum class forward_progress_guarantee { non-movable types into containers like `tuple`, `optional`, and `variant`. 12.
-        struct on-stop-request {
-          in_place_stop_source& stop_src;
-          void operator()() noexcept { stop_src.request_stop(); }
+        struct on-stop-request { // exposition only
+          in_place_stop_source& stop-src; // exposition only
+          void operator()() noexcept { stop-src.request_stop(); }
         };
         
13.
         template<class... T>
-        struct product-type {
+        struct product-type {  // exposition only
           using type0 = T0;      // exposition only
           using type1 = T1;      // exposition only
             ...
@@ -5086,13 +4874,10 @@ enum class forward_progress_guarantee {
 
     14. 
         template <semiregular Tag, movable-value Data = see below, sender... Child>
-        constexpr auto make-sender(Tag, Data&& data, Child&&... child);
+          constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
- 1. *Remarks:* The default template argument for the `Data` template parameter - denotes an unspecified empty trivial class type. - - 2. *Returns:* A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> + 1. *Returns:* A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> where the tag member has been default-initialized and the data and childn... members have been direct initialized from their respective forwarded arguments, where @@ -5136,25 +4921,38 @@ enum class forward_progress_guarantee { impls-for<tag_of_t<Sndr>>::get-env, Index, state-type<Sndr, Rcvr>&, const Rcvr&>>; - template<class Sndr, class Rcvr, class Index> // arguments are not associated entities ([lib.tmpl-heads]) + template<class Sndr, class Rcvr, class Index> requires well-formed<env-type, Index, Sndr, Rcvr> struct basic-receiver { // exposition only - using tag_t = tag_of_t<Sndr>; // exposition only + using tag-type = tag_of_t<Sndr>; // exposition only using receiver_concept = receiver_t; - template<completion-tag Tag, class... Args> - requires cpo-callable<impls-for<tag_t>::complete, - Index, state-type<Sndr, Rcvr>&, Rcvr&, Tag, Args...> - friend void tag_invoke(Tag, basic-receiver&& self, Args&&... args) noexcept { - (void) impls-for<tag_t>::complete( - Index(), self.op_->state_, self.op_->rcvr_, Tag(), std::forward<Args>(args)...); + template<class... Args> + requires cpo-callable<impls-for<tag-type>::complete, + Index, state-type<Sndr, Rcvr>&, Rcvr&, set_value_t, Args...> + void set_value(Args&&... args) && noexcept { + (void) impls-for<tag-type>::complete( + Index(), op_->state_, op_->rcvr_, set_value_t(), std::forward<Args>(args)...); + } + + template<class Error> + requires cpo-callable<impls-for<tag-type>::complete, + Index, state-type<Sndr, Rcvr>&, Rcvr&, set_error_t, Error> + void set_error(Error&& err) && noexcept { + (void) impls-for<tag-type>::complete( + Index(), op_->state_, op_->rcvr_, set_error_t(), std::forward<Error>(err)); } - template<same_as<get_env_t> Tag> - friend auto tag_invoke(Tag, const basic-receiver& self) noexcept - -> env-type<Index, Sndr, Rcvr> { - const auto& rcvr = self.op_->rcvr_; - return impls-for<tag_t>::get-env(Index(), self.op_->state_, rcvr); + void set_stopped() && noexcept + requires cpo-callable<impls-for<tag-type>::complete, + Index, state-type<Sndr, Rcvr>&, Rcvr&, set_stopped_t> { + (void) impls-for<tag-type>::complete( + Index(), op_->state_, op_->rcvr_, set_stopped_t()); + } + + auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> { + const auto& rcvr = op_->rcvr_; + return impls-for<tag-type>::get-env(Index(), op_->state_, rcvr); } basic-operation<Sndr, Rcvr>* op_; // exposition only @@ -5178,11 +4976,11 @@ enum class forward_progress_guarantee { cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr, indices-for<Sndr>>; - template<class Sndr, class Rcvr> // arguments are not associated entities ([lib.tmpl-heads]) + template<class Sndr, class Rcvr> requires well-formed<state-type, Sndr, Rcvr> && well-formed<inner-ops-tuple, Sndr, Rcvr> struct basic-operation { // exposition only - using tag_t = tag_of_t<Sndr>; // exposition only + using tag-type = tag_of_t<Sndr>; // exposition only Rcvr rcvr_; // exposition only state-type<Sndr, Rcvr> state_; // exposition only @@ -5190,38 +4988,34 @@ enum class forward_progress_guarantee { basic-operation(Sndr&& sndr, Rcvr rcvr) // exposition only : rcvr_(std::move(rcvr)) - , state_(impls-for<tag_t>::get-state(std::forward<Sndr>(sndr), rcvr_)) + , state_(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr_)) , inner_ops_(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>())) {} - friend void tag_invoke(start_t, basic-operation& self) noexcept { - auto& [...ops] = self.inner_ops_; - impls-for<tag_t>::start(self.state_, self.rcvr_, ops...); + void start() & noexcept { + auto& [...ops] = inner_ops_; + impls-for<tag-type>::start(state_, rcvr_, ops...); } }; template<class Sndr, class Env> using completion-signatures-for = see below; // exposition only - template<class Tag, class Data, class... Child> // arguments are not associated entities ([lib.tmpl-heads]) + template<class Tag, class Data, class... Child> struct basic-sender { // exposition only using sender_concept = sender_t; - template<same_as<get_env_t> GetEnvTag> - friend decltype(auto) tag_invoke(GetEnvTag, const basic-sender& self) noexcept { + decltype(auto) get_env() const noexcept { return impls-for<Tag>::get-attrs(data, child0, ... childn-1); } - template<same_as<connect_t> ConnectTag, - decays-to<basic-sender> Self, receiver Rcvr> - friend auto tag_invoke(ConnectTag, Self&& self, Rcvr rcvr) - -> basic-operation<Self, Rcvr> { + template<decays-to<basic-sender> Self, receiver Rcvr> + auto connect(this Self&& self, Rcvr rcvr) -> basic-operation<Self, Rcvr> { return {std::forward<Self>(self), std::move(rcvr)}; } - template<same_as<get_completion_signatures_t> GetComplSigsTag, - decays-to<basic-sender> Self, class Env> - friend auto tag_invoke(GetComplSigsTag, Self&& self, Env&& env) noexcept + template<decays-to<basic-sender> Self, class Env> + auto get_completion_signatures(this Self&& self, Env&& env) noexcept -> completion-signatures-for<Self, Env> { return {}; } @@ -5241,6 +5035,9 @@ enum class forward_progress_guarantee { using child-type = decltype((declval<Sndr>().childN)); // exposition only
+ 2. *Remarks:* The default template argument for the `Data` template parameter + denotes an unspecified empty trivial class type. + 3. It is unspecified whether instances of basic-sender can be aggregate initialized. @@ -5334,17 +5131,18 @@ enum class forward_progress_guarantee { template<class Sndr> concept is-sender = // exposition only - derived_from<typename Sndr::sender_concept, sender_t>; + requires { + requires derived_from<typename Sndr::sender_concept, sender_t>; + }; template<class Sndr> - inline constexpr bool enable_sender = is-sender<Sndr>; - - template<is-awaitable<env-promise<empty_env>> Sndr> // [exec.awaitables] - inline constexpr bool enable_sender<Sndr> = true; + concept enable-sender = // exposition only + is-sender<Sndr> || + is-awaitable<Sndr, env-promise<empty_env>>; // [exec.awaitables] template<class Sndr> concept sender = - enable_sender<remove_cvref_t<Sndr>> && + bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint requires (const remove_cvref_t<Sndr>& sndr) { { get_env(sndr) } -> queryable; } && @@ -5356,8 +5154,8 @@ enum class forward_progress_guarantee { sender<Sndr> && queryable<Env> && requires (Sndr&& sndr, Env&& env) { - { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) } -> - valid-completion-signatures; + { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) } + -> valid-completion-signatures; }; template<class Sndr, class Rcvr> @@ -5384,12 +5182,7 @@ enum class forward_progress_guarantee { valid-completion-signatures if it denotes a specialization of the `completion_signatures` class template. -4. Remarks: Pursuant to [namespace.std], users can specialize `enable_sender` to - `true` for cv-unqualified program-defined types that model `sender`, and `false` - for types that do not. Such specializations shall be usable in constant - expressions ([expr.const]) and have type `const bool`. - -5. The exposition-only concepts sender-of and +4. The exposition-only concepts sender-of and sender-of-in define the requirements for a sender type that completes with a given unique set of value result types. @@ -5408,7 +5201,7 @@ enum class forward_progress_guarantee { concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
-6. Let `sndr` be an expression such that `decltype((sndr))` is `Sndr`. The type +5. Let `sndr` be an expression such that `decltype((sndr))` is `Sndr`. The type `tag_of_t` is as follows: - If the declaration `auto&& [tag, data, ...children] = sndr;` would be @@ -5423,7 +5216,7 @@ enum class forward_progress_guarantee { makes it possible to implement this purely in the library. P2141 has already been approved by EWG for C++26. -7. Let sender-for be an exposition-only concept defined as follows: +6. Let sender-for be an exposition-only concept defined as follows:
     template<class Sndr, class Tag>
@@ -5432,15 +5225,18 @@ enum class forward_progress_guarantee {
       same_as<tag_of_t<Sndr>, Tag>;
     
-8. For a type `T`, SET-VALUE-SIG(T) denotes the type +7. For a type `T`, SET-VALUE-SIG(T) denotes the type `set_value_t()` if `T` is *cv* `void`; otherwise, it denotes the type `set_value_t(T)`. -9. Library-provided sender types: - - Always expose an overload of a customization of `connect` - that accepts an rvalue sender. - - Only expose an overload of a customization of `connect` that - accepts an lvalue sender if they model `copy_constructible`. +8. Library-provided sender types: + + - Always expose an overload of a member `connect` that accepts an rvalue + sender. + + - Only expose an overload of a member `connect` that accepts an lvalue + sender if they model `copy_constructible`. + - Model `copy_constructible` if they satisfy `copy_constructible`. ### Awaitable helpers [exec.awaitables] ### {#spec.exec-awaitables} @@ -5493,31 +5289,36 @@ enum class forward_progress_guarantee { - `T` is `bool`, or - `T` is a specialization of `coroutine_handle`. -3. For a subexpression `c` such that `decltype((c))` is type `C`, and +4. For a subexpression `c` such that `decltype((c))` is type `C`, and an lvalue `p` of type `Promise`, await-result-type<C, Promise> denotes the type decltype(GET-AWAITER(c, p).await_resume()). -4. Let with-await-transform be the exposition-only class template: +5. Let with-await-transform be the exposition-only class template:
+    template<class T, class Promise>
+      concept has-as-awaitable = // exposition only
+        requires (T&& t, Promise& p) {
+          { std::forward<T>(t).as_awaitable(p) } -> is-awaitable<Promise&>;
+        };
+
     template<class Derived>
-    struct with-await-transform {
-      template<class T>
-      T&& await_transform(T&& value) noexcept {
-        return std::forward<T>(value);
-      }
+      struct with-await-transform {
+        template<class T>
+          T&& await_transform(T&& value) noexcept {
+            return std::forward<T>(value);
+          }
 
-      template<class T>
-        requires tag_invocable<as_awaitable_t, T, Derived&>
-      auto await_transform(T&& value)
-        noexcept(nothrow_tag_invocable<as_awaitable_t, T, Derived&>)
-        -> tag_invoke_result_t<as_awaitable_t, T, Derived&> {
-        return tag_invoke(as_awaitable, std::forward<T>(value), static_cast<Derived&>(*this));
-      }
-    };
+        template<has-as-awaitable<Derived> T>
+          auto await_transform(T&& value)
+            noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>())))
+            -> decltype(std::forward<T>(value).as_awaitable(declval<Derived&>())) {
+            return std::forward<T>(value).as_awaitable(static_cast<Derived&>(*this));
+          }
+      };
     
-5. Let env-promise be the exposition-only class template: +6. Let env-promise be the exposition-only class template:
     template<class Env>
@@ -5529,7 +5330,7 @@ enum class forward_progress_guarantee {
       void return_void() noexcept;
       coroutine_handle<> unhandled_stopped() noexcept;
 
-      friend const Env& tag_invoke(get_env_t, const env-promise&) noexcept;
+      const Env& get_env() const noexcept;
     };
     
@@ -5663,7 +5464,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> such that `decltype((env))` is `Env`. Then `get_completion_signatures(sndr, env)` is expression-equivalent to: - 1. `tag_invoke_result_t{}` if that + 1. `decltype(sndr.get_completion_signatures(env)){}` if that expression is well-formed, 2. Otherwise, `remove_cvref_t::completion_signatures{}` if that expression is well-formed, @@ -5721,8 +5522,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> coroutine_handle<connect-awaitable-promise>::from_promise(*this)}; } - friend env_of_t<const DR&> tag_invoke(get_env_t, const connect-awaitable-promise& self) noexcept { - return get_env(self.rcvr); + env_of_t<const DR&> get_env() const noexcept { + return execution::get_env(rcvr); } };
@@ -5739,8 +5540,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> : coro(exchange(o.coro, {})) {} ~operation-state-task() { if (coro) coro.destroy(); } - friend void tag_invoke(start_t, operation-state-task& self) noexcept { - self.coro.resume(); + void start() & noexcept { + coro.resume(); } };
@@ -5793,11 +5594,10 @@ template<class Domain, class Tag, sender Sndr, class... Args> `connect(sndr, rcvr)` is ill-formed. Otherwise, the expression `connect(sndr, rcvr)` is expression-equivalent to: - 1. `tag_invoke(connect, sndr, rcvr)` if - connectable-with-tag-invoke<Sndr, Rcvr> is modeled. + 1. `sndr.connect(rcvr)` if that expression is well-formed. - * Mandates: The type of the `tag_invoke` expression above - satisfies `operation_state`. + * Mandates: The type of the expression above satisfies + `operation_state`. 2. Otherwise, connect-awaitable(sndr, rcvr) if that expression is well-formed. @@ -5810,16 +5610,14 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. `schedule` obtains a schedule-sender ([async.ops]) from a scheduler. -2. The name `schedule` denotes a customization point object. For some +2. The name `schedule` denotes a customization point object. For a subexpression `sch`, the expression `schedule(sch)` is expression-equivalent to: - 1. `tag_invoke(schedule, sch)`, if that expression is valid. If the function - selected by `tag_invoke` does not return a sender whose `set_value` - completion scheduler is equivalent to `sch`, the behavior of calling - `schedule(sch)` is undefined. + 1. `sch.schedule()` if that expression is valid. If `sch.schedule()` does + not return a sender whose `set_value` completion scheduler is equal + to `sch`, the behavior of calling `schedule(sch)` is undefined. - * Mandates: The type of the `tag_invoke` expression above - satisfies `sender`. + * Mandates: The type of `sch.schedule()` satisfies `sender`. 2. Otherwise, `schedule(sch)` is ill-formed. @@ -5917,35 +5715,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> requirement applies to any sender returned from a function that is selected by the implementation of such sender adaptor. -6. For any sender type, receiver type, operation state type, queryable type, or - coroutine promise type that is part of the implementation of any sender - adaptor in this subclause and that is a class template, the template - arguments do not contribute to the associated entities - ([basic.lookup.argdep]) of a function call where a specialization of the - class template is an associated entity. - - [*Example:* - -
-    namespace sender-adaptors { // exposition only
-      template<class Sch, class Sndr> // arguments are not associated entities ([lib.tmpl-heads])
-      class on-sender {
-        // ...
-      };
-
-      struct on_t {
-        template<scheduler Sch, sender Sndr>
-        on-sender<Sch, Sndr> operator()(Sch&& sch, Sndr&& sndr) const {
-          // ...
-        }
-      };
-    }
-    inline constexpr sender-adaptors::on_t on{};
-    
- - -- end example] - -7. If a sender returned from a sender adaptor specified in this subclause is +6. If a sender returned from a sender adaptor specified in this subclause is specified to include `set_error_t(Err)` among its set of completion signatures where `decay_t` denotes the type `exception_ptr`, but the implementation does not potentially evaluate an error completion operation with an @@ -6653,20 +6423,42 @@ template<class Domain, class Tag, sender Sndr, class... Args> struct shared-receiver { using receiver_concept = receiver_t; - template<completion-tag Tag, class... Args> - friend void tag_invoke(Tag, shared-receiver&& self, Args&&... args) noexcept { + template<class Tag, class... Args> + void complete(Tag, Args&&... args) noexcept { // exposition only try { using tuple_t = decayed-tuple<Tag, Args...>; - self.sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...); + sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...); } catch (...) { using tuple_t = tuple<set_error_t, exception_ptr>; - self.sh_state->result.template emplace<tuple_t>(set_error, current_exception()); + sh_state->result.template emplace<tuple_t>(set_error, current_exception()); } - self.sh_state->notify(); + sh_state->notify(); + } + + template<class... Args> + void set_value(Args&&... args) && noexcept { + complete(execution::set_value, std::forward<Args>(args)...); + } + + template<class Error> + void set_error(Error&& err) && noexcept { + complete(execution::set_error, std::forward<Error>(err)); + } + + void set_stopped() && noexcept { + complete(execution::set_stopped); } - friend decltype(auto) tag_invoke(get_env_t, const shared-receiver& self) noexcept { - return MAKE-ENV(get_stop_token, self.sh_state->stop_src.get_token()); + struct env { // exposition only + shared-state<Sndr>* sh-state; // exposition only + + in_place_stop_source query(get_stop_token_t) const noexcept { + return sh-state->stop_src.get_token(); + } + }; + + env get_env() const noexcept { + return env{sh_state}; } shared-state<Sndr>* sh_state; @@ -7229,7 +7021,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. `stopped_as_optional` maps an input sender's stopped completion operation into the value completion operation as an empty optional. The input sender's value completion operation is also converted into an optional. The result is a sender that never completes with stopped, reporting cancellation by completing with an empty optional. -2. The name `stopped_as_optional` denotes a customization point object. For some subexpression `sndr`, let `Sndr` be `decltype((sndr))`. +2. The name `stopped_as_optional` denotes a customization point object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. The expression `stopped_as_optional(sndr)` is expression-equivalent to:
@@ -7284,7 +7076,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 1. `start_detached` eagerly starts a sender without the caller needing to manage
     the lifetimes of any objects.
 
-2. The name `start_detached` denotes a customization point object. For some
+2. The name `start_detached` denotes a customization point object. For a
     subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If
     `sender_in` is `false`, `start_detached` is ill-formed.
     Otherwise, the expression `start_detached(sndr)` is expression-equivalent to
@@ -7305,32 +7097,34 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 3. Let `sndr` be a subexpression such that `Sndr` is `decltype((sndr))`, and let
     detached-receiver and
     detached-operation be the following exposition-only
-    class types:
+    class templates:
 
     
+    template<class Sndr>
     struct detached-receiver {
       using receiver_concept = receiver_t;
-      detached-operation* op; // exposition only
+      detached-operation<Sndr>* op; // exposition only
 
-      friend void tag_invoke(set_value_t, detached-receiver&& self) noexcept { delete self.op; }
-      friend void tag_invoke(set_error_t, detached-receiver&&, auto&&) noexcept { terminate(); }
-      friend void tag_invoke(set_stopped_t, detached-receiver&& self) noexcept { delete self.op; }
-      friend empty_env tag_invoke(get_env_t, const detached-receiver&) noexcept { return {}; }
+      void set_value() && noexcept { delete op; }
+      void set_error() && noexcept { terminate(); }
+      void set_stopped() && noexcept { delete op; }
+      empty_env get_env() const noexcept { return {}; }
     };
 
+    template<class Sndr>
     struct detached-operation {
-      connect_result_t<Sndr, detached-receiver> op; // exposition only
+      connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only
 
       explicit detached-operation(Sndr&& sndr)
-        : op(connect(std::forward<Sndr>(sndr), detached-receiver{this}))
+        : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this}))
       {}
     };
     
-4. If sender_to<Sndr, detached-receiver> is `false`, the +4. If sender_to<Sndr, detached-receiver<Sndr>> is `false`, the expression `start_detached.apply_sender(sndr)` is ill-formed; otherwise, it is expression-equivalent to start((new - detached-operation(sndr))->op). + detached-operation<Sndr>(sndr))->op). #### `this_thread::sync_wait` [exec.sync.wait] #### {#spec-execution.senders.consumers.sync_wait} @@ -7343,16 +7137,11 @@ template<class Domain, class Tag, sender Sndr, class... Args> type:
-    template<class Tag>
-    concept get-sched-query = // exposition only
-      one-of<Tag, execution::get_scheduler_t, execution::get_delegatee_scheduler_t>;
-
     struct sync-wait-env {
       execution::run_loop* loop; // exposition only
 
-      friend auto tag_invoke(get-sched-query auto, sync-wait-env self) noexcept {
-        return self.loop->get_scheduler();
-      }
+      auto query(execution::get_scheduler_t) const noexcept { loop->get_scheduler(); }
+      auto query(execution::get_delegatee_scheduler_t) const noexcept { loop->get_scheduler(); }
     };
     
@@ -7407,40 +7196,53 @@ template<class Domain, class Tag, sender Sndr, class... Args> using receiver_concept = receiver_t; sync-wait-state<Sndr>* state; // exposition only - template<class Tag, class... Ts> - void complete(Tag, Ts&&... ts) noexcept; // exposition only + template<class... Args> + void set_value(Args&&... args) && noexcept; - template<completion-tag Tag, class... Ts> - friend void tag_invoke(Tag, sync-wait-receiver&& self, Ts&&... ts) noexcept { - self.complete(Tag(), std::forward<Ts>(ts)...); - self.state->loop.finish(); - } + template<class Error> + void set_error(Error&& err) && noexcept; - friend sync-wait-env tag_invoke(get_env_t, const sync-wait-receiver& self) noexcept { - return {&self.state->loop}; - } + void set_stopped() && noexcept; + + sync-wait-env get_env() const noexcept { return {&state->loop}; } };
- 1. The member sync-wait-receiver::complete behaves as follows: + 1.
+        template<class... Args>
+        void sync-wait-receiver::set_value(Args&&... args) && noexcept;
+        
- 1. If `Tag` is `set_value_t`, evaluates: + 1. *Effects:* Equivalent to:
             try {
-              state->result.emplace(std::forward<Ts>(ts)...);
+              state->result.emplace(std::forward<Args>(args)...);
             } catch (...) {
               state->error = current_exception();
             }
+            state->loop.finish();
             
- 2. Otherwise, if `Tag` is `set_error_t`, evaluates: + 2.
+        template<class Error>
+        void sync-wait-receiver::set_error(Error&& err) && noexcept;
+        
+ + 1. *Effects:* Equivalent to:
-            state->error = AS-EXCEPT-PTR(std::forward(ts)...); // see [exec.general]
+            state->error = AS-EXCEPT-PTR(std::forward<Error>(err)); // see [exec.general]
+            state->loop.finish();
             
- 3. Otherwise, does nothing. + 3.
+        template<class Error>
+        void sync-wait-receiver::set_stopped() && noexcept;
+        
+ + 1. *Effects:* Equivalent to state->loop.finish(). + 6. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If sender_to<Sndr, sync-wait-receiver<Sndr>> is `false`, the @@ -7486,9 +7288,9 @@ template<class Domain, class Tag, sender Sndr, class... Args> expression-equivalent to the following, except `sndr` is evaluated only once: -
-    apply_sender(get-domain-early(sndr), sync_wait_with_variant, sndr)
-    
+
+      apply_sender(get-domain-early(sndr), sync_wait_with_variant, sndr)
+      
Mandates: @@ -7552,50 +7354,26 @@ template<class Domain, class Tag, sender Sndr, class... Args> ## Sender/receiver utilities [exec.utils] ## {#spec-execution.snd_rec_utils} -1. This subclause makes use of the following exposition-only entities: - -
-    // [Editorial note: copy_cvref_t as in [[P1450R3]] -- end note]
-    // Mandates: is_base_of_v<T, remove_reference_t<U>> is true
-    template<class T, class U>
-      copy_cvref_t<U&&, T> c-style-cast(U&& u) noexcept requires decays-to<T, T> {
-        return (copy_cvref_t<U&&, T>) std::forward<U>(u);
-      }
-    
- -2. [Note: The C-style cast in c-style-cast is to disable accessibility checks. -- end note] - ### `execution::receiver_adaptor` [exec.utils.rcvr.adptr] ### {#spec-execution.snd_rec_utils.rcvr_adptr}
-    template<
-        class-type Derived,
-        receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
+    template<class-type Derived, receiver Base = unspecified>
       class receiver_adaptor;
     
-1. `receiver_adaptor` simplifies the implementation of one receiver type in terms of another. It defines `tag_invoke` overloads that forward to named members if they exist, and to the adapted receiver otherwise. - -2. If `Base` is an alias for the unspecified default template argument, then: - - - Let HAS-BASE be `false`, and - - Let GET-BASE(d) be `d.base()`. - - otherwise, let: - - - Let HAS-BASE be `true`, and - - Let GET-BASE(d) be c-style-cast<receiver_adaptor<Derived, Base>>(d).base(). +1. `receiver_adaptor` simplifies the implementation of one receiver type in + terms of another. It defines named member functions that forward to + identically named members in the derived type if they exist, and to the + adapted receiver otherwise. - Let BASE-TYPE(D) be the type of GET-BASE(declval<D>()). +2. Let HAS-BASE be `false` if `Base` is an alias for the + unspecified default template argument; otherwise, it is `true`. -3. `receiver_adaptor` is equivalent to the following: +3. `receiver_adaptor` is as follows:
-    template<
-      class-type Derived,
-      receiver Base = unspecified> // arguments are not associated entities ([lib.tmpl-heads])
+    template<class-type Derived, receiver Base = unspecified>
     class receiver_adaptor {
-      friend Derived;
      public:
       using receiver_concept = receiver_t;
 
@@ -7603,39 +7381,37 @@ template<class Domain, class Tag, sender Sndr, class... Args>
       receiver_adaptor() = default;
       template<class B>
           requires HAS-BASE && constructible_from<Base, B>
-        explicit receiver_adaptor(B&& base) : base_(std::forward<B>(base)) {}
-
-     private:
-      using set_value = unspecified;
-      using set_error = unspecified;
-      using set_stopped = unspecified;
-      using get_env = unspecified;
+        explicit receiver_adaptor(B&& b) : base-rcvr(std::forward<B>(b)) {}
 
       // Member functions
-      template<class Self>
-        requires HAS-BASE
-      decltype(auto) base(this Self&& self) noexcept {
-        return (std::forward<Self>(self).base_);
-      }
+      template<class... Args>
+        void set_value(Args&&... args) && noexcept;
+
+      template<class Error>
+        void set_error(Error&& err) && noexcept;
+
+      void set_stopped() && noexcept;
 
-      // [exec.utils.rcvr.adptr.nonmembers] Non-member functions
-      template<class... As>
-        friend void tag_invoke(set_value_t, Derived&& self, As&&... as) noexcept;
+      decltype(auto) get_env() const noexcept {
+        return execution::get_env(get-base());
+      }
 
-      template<class Err>
-        friend void tag_invoke(set_error_t, Derived&& self, Err&& err) noexcept;
+     private:
+      friend Derived;
 
-      friend void tag_invoke(set_stopped_t, Derived&& self) noexcept;
+      // Private member functions
+      template<class Self>
+        decltype(auto) get-base(this Self&& self) noexcept; // exposition only
 
-      friend decltype(auto) tag_invoke(get_env_t, const Derived& self) noexcept;
+      template<class Self>
+        decltype(auto) base(this Self&& self) noexcept requires HAS-BASE;
 
-      [[no_unique_address]] Base base_; // present if and only if HAS-BASE is true
+      Base base-rcvr; // exposition only, present if and only if HAS-BASE is true
     };
     
-4. [Note: `receiver_adaptor` provides `tag_invoke` overloads on behalf of - the derived class `Derived`, which is incomplete when `receiver_adaptor` is - instantiated.] +4. [Note: The `Derived` template parameter denotes a class type that is + incomplete when `receiver_adaptor` is instantiated.] 5. [Example:
@@ -7643,82 +7419,81 @@ template<class Domain, class Tag, sender Sndr, class... Args>
        completion_signatures<set_value_t(int)>;
 
      template<receiver_of<_int_completion> Rcvr>
-       class my_receiver : receiver_adaptor<my_receiver<Rcvr>, Rcvr> {
-         friend receiver_adaptor<my_receiver, Rcvr>;
-         void set_value() && {
-           set_value(std::move(*this).base(), 42);
+       struct my_receiver
+         : receiver_adaptor<my_receiver<Rcvr>, Rcvr> {
+         explicit my_receiver(Rcvr r)
+           : receiver_adaptor<my_receiver, Rcvr>(std::move(r)) {}
+
+         void set_value() && noexcept {
+           std::execution::set_value(std::move(*this).base(), 42);
          }
-        public:
-         using receiver_adaptor<my_receiver, Rcvr>::receiver_adaptor;
        };
      
-- end example] -#### Non-member functions [exec.utils.rcvr.adptr.nonmembers] #### {#spec-execution.snd_rec_utils.receiver_adaptor.nonmembers} +#### Member functions [exec.utils.rcvr.adptr.members] #### {#spec-execution.snd_rec_utils.receiver_adaptor.members}
-    template<class... As>
-      friend void tag_invoke(set_value_t, Derived&& self, As&&... as) noexcept;
+    template<class... Args>
+      void receiver_adaptor<Derived, Base>::set_value(Args&&... args) && noexcept;
     
- 1. Let `SET-VALUE-MBR` be the expression `std::move(self).set_value(std::forward(as)...)`. - - 2. Constraints: Either `SET-VALUE-MBR` is a valid expression or `typename Derived::set_value` denotes a type and callable<set_value_t, BASE-TYPE(Derived), As...> is `true`. - - 3. Mandates: `SET-VALUE-MBR`, if that expression is valid, is not potentially-throwing. - - 4. Effects: Equivalent to: + 1. Let `e` be the expression + execution::set_value(std::move(get-base()), std::forward<Args>(args)...). - * If `SET-VALUE-MBR` is a valid expression, `SET-VALUE-MBR`; + 2. Constraints: `e` is a well-formed expression. - * Otherwise, set_value(GET-BASE(std::move(self)), std::forward<As>(as)...). + 3. Effects: Equivalent to `e`.
-    template<class Err>
-      friend void tag_invoke(set_error_t, Derived&& self, Err&& err) noexcept;
+    template<class Error>
+      void receiver_adaptor<Derived, Base>::set_error(Error&& err) && noexcept;
     
- 1. Let `SET-ERROR-MBR` be the expression `std::move(self).set_error(std::forward(err))`. - - 2. Constraints: Either `SET-ERROR-MBR` is a valid expression or `typename Derived::set_error` denotes a type and callable<set_error_t, BASE-TYPE(Derived), Err> is `true`. - - 3. Mandates: `SET-ERROR-MBR`, if that expression is valid, is not potentially-throwing. + 1. Let `e` be the expression + execution::set_error(std::move(get-base()), std::forward<Error>(err)). - 4. Effects: Equivalent to: + 2. Constraints: `e` is a well-formed expression. - * If `SET-ERROR-MBR` is a valid expression, `SET-ERROR-MBR`; - - * Otherwise, set_error(GET-BASE(std::move(self)), std::forward<Err>(err)). + 3. Effects: Equivalent to `e`.
-    friend void tag_invoke(set_stopped_t, Derived&& self) noexcept;
+    void receiver_adaptor<Derived, Base>::set_stopped() && noexcept;
     
- 1. Let `SET-STOPPED-MBR` be the expression `std::move(self).set_stopped()`. - - 2. Constraints: Either `SET-STOPPED-MBR` is a valid expression or `typename Derived::set_stopped` denotes a type and callable<set_stopped_t, BASE-TYPE(Derived)> is `true`. - - 3. Mandates: `SET-STOPPED-MBR`, if that expression is valid, is not potentially-throwing. - - 4. Effects: Equivalent to: + 1. Let `e` be the expression + execution::set_stopped(std::move(get-base())). - * If `SET-STOPPED-MBR` is a valid expression, `SET-STOPPED-MBR`; + 2. Constraints: `e` is a well-formed expression. - * Otherwise, set_stopped(GET-BASE(std::move(self))). + 3. Effects: Equivalent to `e`.
-    friend decltype(auto) tag_invoke(get_env_t, const Derived& self) noexcept;
+    template<class Self>
+      decltype(auto) receiver_adaptor<Derived, Base>::get-base(this Self&& self) noexcept;
     
- 1. Constraints: Either `self.get_env()` is a valid expression or `typename Derived::get_env` denotes a type and callable<get_env_t, BASE-TYPE(const Derived&)> is `true`. + 1. Let `e` be the expression + std::forward_like<Self>((Derived&) self).base() if that expression + is well-formed; otherwise, it is + std::forward_like<Self>((receiver_adaptor&) self).base(). + The C-style casts are to disable accessibility checks. - 2. Mandates: `noexcept(self.get_env())` is `true` if it is a valid expression. + 2. Mandates: `is_base_of_v` is `true` and `e` + is a well-formed expression. - 3. Effects: Equivalent to: + 3. Returns: `e`. + +
+    template<class Self>
+      decltype(auto) receiver_adaptor<Derived, Base>::base(this Self&& self) noexcept requires HAS-BASE;
+    
- * If `self.get_env()` is a valid expression, `self.get_env()`; + 1. Let `e` be the expression + std::forward_like<Self>((receiver_adaptor&) self).base-rcvr. + The C-style cast is to disable accessibility checks. - * Otherwise, get_env(GET-BASE(self)). + 3. Returns: (e). ### `execution::completion_signatures` [exec.utils.cmplsigs] ### {#spec-execution.snd_rec_utils.completion_sigs} @@ -7995,7 +7770,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> * The expression get_completion_scheduler<C>(get_env(sndr)) is not potentially-throwing, has type run-loop-scheduler, and compares equal to the run-loop-scheduler instance from which sndr was obtained.
-  template<receiver_of<completion_signatures<set_value_t()>> Rcvr> // arguments are not associated entities ([lib.tmpl-heads])
+  template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
     struct run-loop-opstate;
   
@@ -8131,7 +7906,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. The type sender-awaitable<Sndr, Promise> is equivalent to the following:
-        template<class Sndr, class Promise> // arguments are not associated entities ([lib.tmpl-heads])
+        template<class Sndr, class Promise>
         class sender-awaitable {
           struct unit {};
           using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>;
@@ -8186,7 +7961,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                 static_cast<coroutine_handle<>>(rcvr.continuation_.promise().unhandled_stopped()).resume().
 
               4. For any expression `tag` whose type satisfies forwarding-query
-                  and for any pack of subexpressions `as`, `tag_invoke(tag, get_env(crcvr), as...)`
+                  and for any pack of subexpressions `as`, `get_env(crcvr).query(tag, as...)`
                   is expression-equivalent to tag(get_env(as_const(crcvr.continuation_.promise())),
                   as...) when that expression is well-formed.
 
@@ -8205,11 +7980,15 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                   return std::forward<value_t>(get<1>(result_));
                 
-2. `as_awaitable` is a customization point object. For some subexpressions `expr` and `p` where `p` is an lvalue, `Expr` names the type `decltype((expr))` and `Promise` names the type `decltype((p))`, `as_awaitable(expr, p)` is expression-equivalent to the following: +2. `as_awaitable` is a customization point object. For some subexpressions + `expr` and `p` where `p` is an lvalue, `Expr` names the type + `decltype((expr))` and `Promise` names the type `decltype((p))`, + `as_awaitable(expr, p)` is expression-equivalent to the following: - 1. `tag_invoke(as_awaitable, expr, p)` if that expression is well-formed. + 1. `expr.as_awaitable(p)` if that expression is well-formed. - * Mandates: is-awaitable<A, Promise> is `true`, where `A` is the type of the `tag_invoke` expression above. + * Mandates: is-awaitable<A, Promise> is + `true`, where `A` is the type of the expression above. 2. Otherwise, `expr` if is-awaitable<Expr, U> is `true`, where U is an unspecified class type that From d08cc063a846ad164e58cad3f9db1a3f7f48e11c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 20 Mar 2024 12:21:37 -0700 Subject: [PATCH 38/89] update the prose now that `tag_invoke` has been retired --- execution.bs | 3363 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 2162 insertions(+), 1201 deletions(-) diff --git a/execution.bs b/execution.bs index cd1c294..61d51ba 100644 --- a/execution.bs +++ b/execution.bs @@ -135,23 +135,41 @@ This paper proposes a self-contained design for a Standard C++ framework for man ## Motivation ## {#motivation} -Today, C++ software is increasingly asynchronous and parallel, a trend that is likely to only continue going forward. -Asynchrony and parallelism appears everywhere, from processor hardware interfaces, to networking, to file I/O, to GUIs, to accelerators. -Every C++ domain and every platform needs to deal with asynchrony and parallelism, from scientific computing to video games to financial services, from the smallest mobile devices to your laptop to GPUs in the world's fastest supercomputer. - -While the C++ Standard Library has a rich set of concurrency primitives (`std::atomic`, `std::mutex`, `std::counting_semaphore`, etc) and lower level building blocks (`std::thread`, etc), we lack a Standard vocabulary and framework for asynchrony and parallelism that C++ programmers desperately need. -`std::async`/`std::future`/`std::promise`, C++11's intended exposure for asynchrony, is inefficient, hard to use correctly, and severely lacking in genericity, making it unusable in many contexts. -We introduced parallel algorithms to the C++ Standard Library in C++17, and while they are an excellent start, they are all inherently synchronous and not composable. - -This paper proposes a Standard C++ model for asynchrony, based around three key abstractions: schedulers, senders, and receivers, and a set of customizable asynchronous algorithms. +Today, C++ software is increasingly asynchronous and parallel, a trend that is +likely to only continue going forward. Asynchrony and parallelism appears +everywhere, from processor hardware interfaces, to networking, to file I/O, to +GUIs, to accelerators. Every C++ domain and every platform needs to deal with +asynchrony and parallelism, from scientific computing to video games to +financial services, from the smallest mobile devices to your laptop to GPUs in +the world's fastest supercomputer. + +While the C++ Standard Library has a rich set of concurrency primitives +(`std::atomic`, `std::mutex`, `std::counting_semaphore`, etc) and lower level +building blocks (`std::thread`, etc), we lack a Standard vocabulary and +framework for asynchrony and parallelism that C++ programmers desperately need. +`std::async`/`std::future`/`std::promise`, C++11's intended exposure for +asynchrony, is inefficient, hard to use correctly, and severely lacking in +genericity, making it unusable in many contexts. We introduced parallel +algorithms to the C++ Standard Library in C++17, and while they are an excellent +start, they are all inherently synchronous and not composable. + +This paper proposes a Standard C++ model for asynchrony based around three key +abstractions: schedulers, senders, and receivers, and a set of customizable +asynchronous algorithms. ## Priorities ## {#priorities} -* Be composable and generic, allowing users to write code that can be used with many different types of execution resources. -* Encapsulate common asynchronous patterns in customizable and reusable algorithms, so users don't have to invent things themselves. +* Be composable and generic, allowing users to write code that can be used with + many different types of execution resources. +* Encapsulate common asynchronous patterns in customizable and reusable + algorithms, so users don't have to invent things themselves. * Make it easy to be correct by construction. -* Support the diversity of execution resources and execution agents, because not all execution agents are created equal; some are less capable than others, but not less important. -* Allow everything to be customized by an execution resource, including transfer to other execution resources, but don't require that execution resources customize everything. +* Support the diversity of execution resources and execution agents, because not + all execution agents are created equal; some are less capable than others, + but not less important. +* Allow everything to be customized by an execution resource, including transfer + to other execution resources, but don't require that execution resources + customize everything. * Care about all reasonable use cases, domains and platforms. * Errors must be propagated, but error handling must not present a burden. * Support cancellation, which is not an error. @@ -160,7 +178,11 @@ This paper proposes a Standard C++ model for asynchrony, based around three key ## Examples: End User ## {#example-end-user} -In this section we demonstrate the end-user experience of asynchronous programming directly with the sender algorithms presented in this paper. See [[#design-sender-factories]], [[#design-sender-adaptors]], and [[#design-sender-consumers]] for short explanations of the algorithms used in these code examples. +In this section we demonstrate the end-user experience of asynchronous +programming directly with the sender algorithms presented in this paper. See +[[#design-sender-factories]], [[#design-sender-adaptors]], and +[[#design-sender-consumers]] for short explanations of the algorithms used in +these code examples. ### Hello world ### {#example-hello-world} @@ -181,11 +203,34 @@ auto [i] = this_thread::sync_wait(add_42).value(); // This example demonstrates the basics of schedulers, senders, and receivers: -1. First we need to get a scheduler from somewhere, such as a thread pool. A scheduler is a lightweight handle to an execution resource. -2. To start a chain of work on a scheduler, we call [[#design-sender-factory-schedule]], which returns a sender that completes on the scheduler. A sender describes asynchronous work and sends a signal (value, error, or stopped) to some recipient(s) when that work completes. -3. We use sender algorithms to produce senders and compose asynchronous work. [[#design-sender-adaptor-then]] is a sender adaptor that takes an input sender and a `std::invocable`, and calls the `std::invocable` on the signal sent by the input sender. The sender returned by `then` sends the result of that invocation. In this case, the input sender came from `schedule`, so its `void`, meaning it won't send us a value, so our `std::invocable` takes no parameters. But we return an `int`, which will be sent to the next recipient. -4. Now, we add another operation to the chain, again using [[#design-sender-adaptor-then]]. This time, we get sent a value - the `int` from the previous step. We add `42` to it, and then return the result. -5. Finally, we're ready to submit the entire asynchronous pipeline and wait for its completion. Everything up until this point has been completely asynchronous; the work may not have even started yet. To ensure the work has started and then block pending its completion, we use [[#design-sender-consumer-sync_wait]], which will either return a `std::optional>` with the value sent by the last sender, or an empty `std::optional` if the last sender sent a stopped signal, or it throws an exception if the last sender sent an error. +1. First we need to get a scheduler from somewhere, such as a thread pool. A + scheduler is a lightweight handle to an execution resource. + +2. To start a chain of work on a scheduler, we call + [[#design-sender-factory-schedule]], which returns a sender that completes on + the scheduler. A sender describes asynchronous work and sends a signal + (value, error, or stopped) to some recipient(s) when that work completes. + +3. We use sender algorithms to produce senders and compose asynchronous work. + [[#design-sender-adaptor-then]] is a sender adaptor that takes an input + sender and a `std::invocable`, and calls the `std::invocable` on the signal + sent by the input sender. The sender returned by `then` sends the result of + that invocation. In this case, the input sender came from `schedule`, so its + `void`, meaning it won't send us a value, so our `std::invocable` takes no + parameters. But we return an `int`, which will be sent to the next recipient. + +4. Now, we add another operation to the chain, again using + [[#design-sender-adaptor-then]]. This time, we get sent a value - the `int` + from the previous step. We add `42` to it, and then return the result. + +5. Finally, we're ready to submit the entire asynchronous pipeline and wait for + its completion. Everything up until this point has been completely + asynchronous; the work may not have even started yet. To ensure the work has + started and then block pending its completion, we use + [[#design-sender-consumer-sync_wait]], which will either return a + `std::optional>` with the value sent by the last sender, or + an empty `std::optional` if the last sender sent a stopped signal, or it + throws an exception if the last sender sent an error. ### Asynchronous inclusive scan ### {#example-async-inclusive-scan} @@ -236,21 +281,54 @@ sender auto async_inclusive_scan(scheduler auto sch, // This example builds an asynchronous computation of an inclusive scan: -1. It scans a sequence of `double`s (represented as the `std::span` `input`) and stores the result in another sequence of `double`s (represented as `std::span` `output`). -2. It takes a scheduler, which specifies what execution resource the scan should be launched on. -3. It also takes a `tile_count` parameter that controls the number of execution agents that will be spawned. -4. First we need to allocate temporary storage needed for the algorithm, which we'll do with a `std::vector`, `partials`. We need one `double` of temporary storage for each execution agent we create. -5. Next we'll create our initial sender with [[#design-sender-factory-just]] and [[#design-sender-adaptor-transfer]]. These senders will send the temporary storage, which we've moved into the sender. The sender has a completion scheduler of `sch`, which means the next item in the chain will use `sch`. -6. Senders and sender adaptors support composition via `operator|`, similar to C++ ranges. We'll use `operator|` to attach the next piece of work, which will spawn `tile_count` execution agents using [[#design-sender-adaptor-bulk]] (see [[#design-pipeable]] for details). -7. Each agent will call a `std::invocable`, passing it two arguments. The first is the agent's index (`i`) in the [[#design-sender-adaptor-bulk]] operation, in this case a unique integer in `[0, tile_count)`. The second argument is what the input sender sent - the temporary storage. -8. We start by computing the start and end of the range of input and output elements that this agent is responsible for, based on our agent index. -9. Then we do a sequential `std::inclusive_scan` over our elements. We store the scan result for our last element, which is the sum of all of our elements, in our temporary storage `partials`. -10. After all computation in that initial [[#design-sender-adaptor-bulk]] pass has completed, every one of the spawned execution agents will have written the sum of its elements into its slot in `partials`. -11. Now we need to scan all of the values in `partials`. We'll do that with a single execution agent which will execute after the [[#design-sender-adaptor-bulk]] completes. We create that execution agent with [[#design-sender-adaptor-then]]. -12. [[#design-sender-adaptor-then]] takes an input sender and an `std::invocable` and calls the `std::invocable` with the value sent by the input sender. Inside our `std::invocable`, we call `std::inclusive_scan` on `partials`, which the input senders will send to us. +1. It scans a sequence of `double`s (represented as the `std::span` `input`) and stores the result in another sequence of `double`s + (represented as `std::span` `output`). +2. It takes a scheduler, which specifies what execution resource the scan should + be launched on. +3. It also takes a `tile_count` parameter that controls the number of execution + agents that will be spawned. +4. First we need to allocate temporary storage needed for the algorithm, which + we'll do with a `std::vector`, `partials`. We need one `double` of temporary + storage for each execution agent we create. +5. Next we'll create our initial sender with [[#design-sender-factory-just]] and + [[#design-sender-adaptor-transfer]]. These senders will send the temporary + storage, which we've moved into the sender. The sender has a completion + scheduler of `sch`, which means the next item in the chain will use `sch`. +6. Senders and sender adaptors support composition via `operator|`, similar to + C++ ranges. We'll use `operator|` to attach the next piece of work, which + will spawn `tile_count` execution agents using + [[#design-sender-adaptor-bulk]] (see [[#design-pipeable]] for details). +7. Each agent will call a `std::invocable`, passing it two arguments. The first + is the agent's index (`i`) in the [[#design-sender-adaptor-bulk]] operation, + in this case a unique integer in `[0, tile_count)`. The second argument is + what the input sender sent - the temporary storage. +8. We start by computing the start and end of the range of input and output + elements that this agent is responsible for, based on our agent index. +9. Then we do a sequential `std::inclusive_scan` over our elements. We store the + scan result for our last element, which is the sum of all of our elements, + in our temporary storage `partials`. +10. After all computation in that initial [[#design-sender-adaptor-bulk]] pass + has completed, every one of the spawned execution agents will have written + the sum of its elements into its slot in `partials`. +11. Now we need to scan all of the values in `partials`. We'll do that with a + single execution agent which will execute after the + [[#design-sender-adaptor-bulk]] completes. We create that execution agent + with [[#design-sender-adaptor-then]]. +12. [[#design-sender-adaptor-then]] takes an input sender and an + `std::invocable` and calls the `std::invocable` with the value sent by the + input sender. Inside our `std::invocable`, we call `std::inclusive_scan` + on `partials`, which the input senders will send to us. 13. Then we return `partials`, which the next phase will need. -14. Finally we do another [[#design-sender-adaptor-bulk]] of the same shape as before. In this [[#design-sender-adaptor-bulk]], we will use the scanned values in `partials` to integrate the sums from other tiles into our elements, completing the inclusive scan. -15. `async_inclusive_scan` returns a sender that sends the output `std::span`. A consumer of the algorithm can chain additional work that uses the scan result. At the point at which `async_inclusive_scan` returns, the computation may not have completed. In fact, it may not have even started. +14. Finally we do another [[#design-sender-adaptor-bulk]] of the same shape as + before. In this [[#design-sender-adaptor-bulk]], we will use the scanned + values in `partials` to integrate the sums from other tiles into our + elements, completing the inclusive scan. +15. `async_inclusive_scan` returns a sender that sends the output + `std::span`. A consumer of the algorithm can chain additional work + that uses the scan result. At the point at which `async_inclusive_scan` + returns, the computation may not have completed. In fact, it may not have + even started. ### Asynchronous dynamically-sized read ### {#example-async-dynamically-sized-read} @@ -287,28 +365,57 @@ sender_of auto async_read_array(auto handle) { // } ``` -This example demonstrates a common asynchronous I/O pattern - reading a payload of a dynamic size by first reading the size, then reading the number of bytes specified by the size: - -1. `async_read` is a pipeable sender adaptor. It's a customization point object, but this is what it's call signature looks like. It takes a sender parameter which must send an input buffer in the form of a `std::span`, and a handle to an I/O context. It will asynchronously read into the input buffer, up to the size of the `std::span`. It returns a sender which will send the number of bytes read once the read completes. -2. `async_read_array` takes an I/O handle and reads a size from it, and then a buffer of that many bytes. It returns a sender that sends a `dynamic_buffer` object that owns the data that was sent. -3. `dynamic_buffer` is an aggregate struct that contains a `std::unique_ptr` and a size. -4. The first thing we do inside of `async_read_array` is create a sender that will send a new, empty `dynamic_array` object using [[#design-sender-factory-just]]. We can attach more work to the pipeline using `operator|` composition (see [[#design-pipeable]] for details). -5. We need the lifetime of this `dynamic_array` object to last for the entire pipeline. So, we use `let_value`, which takes an input sender and a `std::invocable` that must return a sender itself (see [[#design-sender-adaptor-let]] for details). `let_value` sends the value from the input sender to the `std::invocable`. Critically, the lifetime of the sent object will last until the sender returned by the `std::invocable` completes. -6. Inside of the `let_value` `std::invocable`, we have the rest of our logic. First, we want to initiate an `async_read` of the buffer size. To do that, we need to send a `std::span` pointing to `buf.size`. We can do that with [[#design-sender-factory-just]]. -7. We chain the `async_read` onto the [[#design-sender-factory-just]] sender with `operator|`. -8. Next, we pipe a `std::invocable` that will be invoked after the `async_read` completes using [[#design-sender-adaptor-then]]. +This example demonstrates a common asynchronous I/O pattern - reading a payload +of a dynamic size by first reading the size, then reading the number of bytes +specified by the size: + +1. `async_read` is a pipeable sender adaptor. It's a customization point object, + but this is what it's call signature looks like. It takes a sender parameter + which must send an input buffer in the form of a `std::span`, and + a handle to an I/O context. It will asynchronously read into the input + buffer, up to the size of the `std::span`. It returns a sender which will + send the number of bytes read once the read completes. +2. `async_read_array` takes an I/O handle and reads a size from it, and then a + buffer of that many bytes. It returns a sender that sends a `dynamic_buffer` + object that owns the data that was sent. +3. `dynamic_buffer` is an aggregate struct that contains a + `std::unique_ptr` and a size. +4. The first thing we do inside of `async_read_array` is create a sender that + will send a new, empty `dynamic_array` object using + [[#design-sender-factory-just]]. We can attach more work to the pipeline + using `operator|` composition (see [[#design-pipeable]] for details). +5. We need the lifetime of this `dynamic_array` object to last for the entire + pipeline. So, we use `let_value`, which takes an input sender and a + `std::invocable` that must return a sender itself (see + [[#design-sender-adaptor-let]] for details). `let_value` sends the value + from the input sender to the `std::invocable`. Critically, the lifetime of + the sent object will last until the sender returned by the `std::invocable` + completes. +6. Inside of the `let_value` `std::invocable`, we have the rest of our logic. + First, we want to initiate an `async_read` of the buffer size. To do that, + we need to send a `std::span` pointing to `buf.size`. We can do that with + [[#design-sender-factory-just]]. +7. We chain the `async_read` onto the [[#design-sender-factory-just]] sender + with `operator|`. +8. Next, we pipe a `std::invocable` that will be invoked after the `async_read` + completes using [[#design-sender-adaptor-then]]. 9. That `std::invocable` gets sent the number of bytes read. 10. We need to check that the number of bytes read is what we expected. 11. Now that we have read the size of the data, we can allocate storage for it. -12. We return a `std::span` to the storage for the data from the `std::invocable`. This will be sent to the next recipient in the pipeline. +12. We return a `std::span` to the storage for the data from the + `std::invocable`. This will be sent to the next recipient in the pipeline. 13. And that recipient will be another `async_read`, which will read the data. -14. Once the data has been read, in another [[#design-sender-adaptor-then]], we confirm that we read the right number of bytes. -15. Finally, we move out of and return our `dynamic_buffer` object. It will get sent by the sender returned by `async_read_array`. We can attach more things to that sender to use the data in the buffer. +14. Once the data has been read, in another [[#design-sender-adaptor-then]], we + confirm that we read the right number of bytes. +15. Finally, we move out of and return our `dynamic_buffer` object. It will get + sent by the sender returned by `async_read_array`. We can attach more + things to that sender to use the data in the buffer. ## Asynchronous Windows socket `recv` ## {#example-async-windows-socket-recv} -To get a better feel for how this interface might be used by low-level operations see this example implementation -of a cancellable `async_recv()` operation for a Windows Socket. +To get a better feel for how this interface might be used by low-level +operations see this example implementation of a cancellable `async_recv()` +operation for a Windows Socket. ```c++ struct operation_base : WSAOVERALAPPED { @@ -333,40 +440,40 @@ struct recv_op : operation_base { buffer.buf = static_cast(data); } - friend void tag_invoke(std::execution::start_t, recv_op& self) noexcept { + void start() & noexcept { // Avoid even calling WSARecv() if operation already cancelled auto st = std::execution::get_stop_token( - std::execution::get_env(self.receiver)); + std::execution::get_env(receiver)); if (st.stop_requested()) { - std::execution::set_stopped(std::move(self.receiver)); + std::execution::set_stopped(std::move(receiver)); return; } // Store and cache result here in case it changes during execution const bool stopPossible = st.stop_possible(); if (!stopPossible) { - self.ready.store(true, std::memory_order_relaxed); + ready.store(true, std::memory_order_relaxed); } // Launch the operation DWORD bytesTransferred = 0; DWORD flags = 0; - int result = WSARecv(self.sock, &self.buffer, 1, &bytesTransferred, &flags, - static_cast(&self), NULL); + int result = WSARecv(sock, &buffer, 1, &bytesTransferred, &flags, + static_cast(this), NULL); if (result == SOCKET_ERROR) { int errorCode = WSAGetLastError(); if (errorCode != WSA_IO_PENDING) { if (errorCode == WSA_OPERATION_ABORTED) { - std::execution::set_stopped(std::move(self.receiver)); + std::execution::set_stopped(std::move(receiver)); } else { - std::execution::set_error(std::move(self.receiver), + std::execution::set_error(std::move(receiver), std::error_code(errorCode, std::system_category())); } return; } } else { // Completed synchronously (assuming FILE_SKIP_COMPLETION_PORT_ON_SUCCESS has been set) - execution::set_value(std::move(self.receiver), bytesTransferred); + execution::set_value(std::move(receiver), bytesTransferred); return; } @@ -374,20 +481,20 @@ struct recv_op : operation_base { // May be completing concurrently on another thread already. if (stopPossible) { // Register the stop callback - self.stopCallback.emplace(std::move(st), cancel_cb{self}); + stopCallback.emplace(std::move(st), cancel_cb{self}); // Mark as 'completed' - if (self.ready.load(std::memory_order_acquire) || - self.ready.exchange(true, std::memory_order_acq_rel)) { + if (ready.load(std::memory_order_acquire) || + ready.exchange(true, std::memory_order_acq_rel)) { // Already completed on another thread - self.stopCallback.reset(); + stopCallback.reset(); - BOOL ok = WSAGetOverlappedResult(self.sock, (WSAOVERLAPPED*)&self, &bytesTransferred, FALSE, &flags); + BOOL ok = WSAGetOverlappedResult(sock, (WSAOVERLAPPED*)&self, &bytesTransferred, FALSE, &flags); if (ok) { - std::execution::set_value(std::move(self.receiver), bytesTransferred); + std::execution::set_value(std::move(receiver), bytesTransferred); } else { int errorCode = WSAGetLastError(); - std::execution::set_error(std::move(self.receiver), + std::execution::set_error(std::move(receiver), std::error_code(errorCode, std::system_category())); } } @@ -405,16 +512,16 @@ struct recv_op : operation_base { static void on_complete(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept { recv_op& self = *static_cast(op); - if (ready.load(std::memory_order_acquire) || - ready.exchange(true, std::memory_order_acq_rel)) { + if (self.ready.load(std::memory_order_acquire) || + self.ready.exchange(true, std::memory_order_acq_rel)) { // Unsubscribe any stop-callback so we know that CancelIoEx() is not accessing 'op' // any more - stopCallback.reset(); + self.stopCallback.reset(); if (errorCode == 0) { - std::execution::set_value(std::move(receiver), bytesTransferred); + std::execution::set_value(std::move(self.receiver), bytesTransferred); } else { - std::execution::set_error(std::move(receiver), + std::execution::set_error(std::move(self.receiver), std::error_code(errorCode, std::system_category())); } } @@ -435,10 +542,8 @@ struct recv_sender { size_t len; template - friend recv_op tag_invoke(std::execution::connect_t, - const recv_sender& s, - Receiver r) { - return recv_op{s.sock, s.data, s.len, std::move(r)}; + recv_op connect(Receiver r) const { + return recv_op{sock, data, len, std::move(r)}; } }; @@ -451,29 +556,52 @@ recv_sender async_recv(SOCKET s, void* data, size_t len) { #### Sudoku solver #### {#example-sudoku} -This example comes from Kirk Shoop, who ported an example from TBB's documentation to sender/receiver in his fork of the libunifex repo. It is a Sudoku solver that uses a configurable number of threads to explore the search space for solutions. +This example comes from Kirk Shoop, who ported an example from TBB's +documentation to sender/receiver in his fork of the libunifex repo. It is a +Sudoku solver that uses a configurable number of threads to explore the search +space for solutions. -The sender/receiver-based Sudoku solver can be found [here](https://github.com/kirkshoop/libunifex/blob/sudoku/examples/sudoku.cpp). Some things that are worth noting about Kirk's solution: +The sender/receiver-based Sudoku solver can be found +[here](https://github.com/kirkshoop/libunifex/blob/sudoku/examples/sudoku.cpp). +Some things that are worth noting about Kirk's solution: -1. Although it schedules asychronous work onto a thread pool, and each unit of work will schedule more work, its use of structured concurrency patterns make reference counting unnecessary. The solution does not make use of `shared_ptr`. +1. Although it schedules asychronous work onto a thread pool, and each unit of + work will schedule more work, its use of structured concurrency patterns + make reference counting unnecessary. The solution does not make use of + `shared_ptr`. -2. In addition to eliminating the need for reference counting, the use of structured concurrency makes it easy to ensure that resources are cleaned up on all code paths. In contrast, the TBB example that inspired this one [leaks memory](https://github.com/oneapi-src/oneTBB/issues/568). +2. In addition to eliminating the need for reference counting, the use of + structured concurrency makes it easy to ensure that resources are cleaned up + on all code paths. In contrast, the TBB example that inspired this one + [leaks memory](https://github.com/oneapi-src/oneTBB/issues/568). -For comparison, the TBB-based Sudoku solver can be found [here](https://github.com/oneapi-src/oneTBB/blob/40a9a1060069d37d5f66912c6ee4cf165144774b/examples/task_group/sudoku/sudoku.cpp). +For comparison, the TBB-based Sudoku solver can be found +[here](https://github.com/oneapi-src/oneTBB/blob/40a9a1060069d37d5f66912c6ee4cf165144774b/examples/task_group/sudoku/sudoku.cpp). #### File copy #### {#example-file-copy} -This example also comes from Kirk Shoop which uses sender/receiver to recursively copy the files a directory tree. It demonstrates how sender/receiver can be used to do IO, using a scheduler that schedules work on Linux's io_uring. +This example also comes from Kirk Shoop which uses sender/receiver to +recursively copy the files a directory tree. It demonstrates how sender/receiver +can be used to do IO, using a scheduler that schedules work on Linux's io_uring. -As with the Sudoku example, this example obviates the need for reference counting by employing structured concurrency. It uses iteration with an upper limit to avoid having too many open file handles. +As with the Sudoku example, this example obviates the need for reference +counting by employing structured concurrency. It uses iteration with an upper +limit to avoid having too many open file handles. -You can find the example [here](https://github.com/kirkshoop/libunifex/blob/filecopy/examples/file_copy.cpp). +You can find the example +[here](https://github.com/kirkshoop/libunifex/blob/filecopy/examples/file_copy.cpp). #### Echo server #### {#example-echo-server} -Dietmar Kuehl has a hobby project that implements networking APIs on top of sender/receiver. He recently implemented an echo server as a demo. His echo server code can be found [here](https://github.com/dietmarkuehl/kuhllib/blob/main/src/examples/echo_server.cpp). +Dietmar Kuehl has proposed networking APIs that use the sender/receiver +abstraction (see \[P2762](https://wg21.link/P2762)). He has implemented an echo +server as a demo. His echo server code can be found +[here](https://github.com/dietmarkuehl/kuhllib/blob/main/src/examples/echo_server.cpp). -Below, I show the part of the echo server code. This code is executed for each client that connects to the echo server. In a loop, it reads input from a socket and echos the input back to the same socket. All of this, including the loop, is implemented with generic async algorithms. +Below, I show the part of the echo server code. This code is executed for each +client that connects to the echo server. In a loop, it reads input from a socket +and echos the input back to the same socket. All of this, including the loop, is +implemented with generic async algorithms.
     outstanding.start(
@@ -498,101 +626,115 @@ Below, I show the part of the echo server code. This code is executed for each c
     );
     
-In this code, `NN::async_read_some` and `NN::async_write_some` are asynchronous socket-based networking APIs that return senders. `EX::repeat_effect_until`, `EX::let_value`, and `EX::then` are fully generic sender adaptor algorithms that accept and return senders. +In this code, `NN::async_read_some` and `NN::async_write_some` are asynchronous +socket-based networking APIs that return senders. `EX::repeat_effect_until`, +`EX::let_value`, and `EX::then` are fully generic sender adaptor algorithms that +accept and return senders. -This is a good example of seamless composition of async IO functions with non-IO operations. And by composing the senders in this structured way, all the state for the composite operation -- the `repeat_effect_until` expression and all its child operations -- is stored altogether in a single object. +This is a good example of seamless composition of async IO functions with non-IO +operations. And by composing the senders in this structured way, all the state +for the composite operation -- the `repeat_effect_until` expression and all its +child operations -- is stored altogether in a single object. ## Examples: Algorithms ## {#example-algorithm} -In this section we show a few simple sender/receiver-based algorithm implementations. +In this section we show a few simple sender/receiver-based algorithm +implementations. ### `then` ### {#example-then} ```c++ -namespace exec = std::execution; +namespace stdexec = std::execution; template class _then_receiver - : exec::receiver_adaptor<_then_receiver, R> { - friend exec::receiver_adaptor<_then_receiver, R>; + : public stdexec::receiver_adaptor<_then_receiver, R> { F f_; - // Customize set_value by invoking the callable and passing the result to the inner receiver - template - void set_value(As&&... as) && noexcept try { - exec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...)); - } catch(...) { - exec::set_error(std::move(*this).base(), std::current_exception()); - } - public: _then_receiver(R r, F f) - : exec::receiver_adaptor<_then_receiver, R>{std::move(r)} + : stdexec::receiver_adaptor<_then_receiver, R>{std::move(r)} , f_(std::move(f)) {} + + // Customize set_value by invoking the callable and passing the result to the inner receiver + template + requires std::invocable + void set_value(As&&... as) && noexcept { + try { + stdexec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...)); + } catch(...) { + stdexec::set_error(std::move(*this).base(), std::current_exception()); + } + } }; -template +template struct _then_sender { - using sender_concept = exec::sender_t; + using sender_concept = stdexec::sender_t; S s_; F f_; template - using _set_value_t = exec::completion_signatures< - exec::set_value_t(std::invoke_result_t)>; + using _set_value_t = stdexec::completion_signatures< + stdexec::set_value_t(std::invoke_result_t)>; // Compute the completion signatures template - friend auto tag_invoke(exec::get_completion_signatures_t, _then_sender&&, Env) - -> exec::transform_completion_signatures_of, - _set_value_t>; + auto get_completion_signatures(Env&& env) && noexcept + -> stdexec::transform_completion_signatures_of, + _set_value_t> { + return {}; + } // Connect: - template - friend auto tag_invoke(exec::connect_t, _then_sender&& self, R r) - -> exec::connect_result_t> { - return exec::connect( - (S&&) self.s_, _then_receiver{(R&&) r, (F&&) self.f_}); + template + auto connect(R r) && -> stdexec::connect_result_t> { + return stdexec::connect( + (S&&) s_, _then_receiver{(R&&) r, (F&&) f_}); } - friend decltype(auto) tag_invoke(get_env_t, const _then_sender& self) noexcept { + decltype(auto) get_env() const noexcept { return get_env(self.s_); } }; -template -exec::sender auto then(S s, F f) { +template +stdexec::sender auto then(S s, F f) { return _then_sender{(S&&) s, (F&&) f}; } ``` -This code builds a `then` algorithm that transforms the value(s) from the input sender -with a transformation function. The result of the transformation becomes the new value. -The other receiver functions (`set_error` and `set_stopped`), as well as all receiver queries, -are passed through unchanged. +This code builds a `then` algorithm that transforms the value(s) from the input +sender with a transformation function. The result of the transformation becomes +the new value. The other receiver functions (`set_error` and `set_stopped`), as +well as all receiver queries, are passed through unchanged. In detail, it does the following: 1. Defines a receiver in terms of `execution::receiver_adaptor` that aggregates another receiver and an invocable that: - * Defines a constrained `tag_invoke` overload for transforming the value - channel. - * Defines another constrained overload of `tag_invoke` that passes all other - customizations through unchanged. + * Defines a constrained `set_value` member function for transforming the + value channel. + * Delegates `set_error` and `set_stopped` to the inner receiver. - The `tag_invoke` overloads are actually implemented by - `execution::receiver_adaptor`; they dispatch either to named members, as - shown above with `_then_receiver::set_value`, or to the adapted receiver. -2. Defines a sender that aggregates another sender and the invocable, which defines a `tag_invoke` customization for `std::execution::connect` that wraps the incoming receiver in the receiver from (1) and passes it and the incoming sender to `std::execution::connect`, returning the result. It also defines a `tag_invoke` customization of `get_completion_signatures` that declares the sender's completion signatures when executed within a particular environment. + The `set_error` and `set_stopped` member functions are provided by + `receiver_adaptor`. + +2. Defines a sender that aggregates another sender and the invocable, which + defines a `connect` member function that wraps the incoming receiver in the + receiver from (1) and passes it and the incoming sender to + `std::execution::connect`, returning the result. It also defines a + `get_completion_signatures` member function that declares the sender's + completion signatures when executed within a particular environment. ### `retry` ### {#example-retry} ```c++ using namespace std; -namespace exec = execution; +namespace stdexec = execution; -template +template concept _decays_to = same_as, To>; // _conv needed so we can emplace construct non-movable types into @@ -608,18 +750,18 @@ struct _conv { }; template -struct _op; +struct _retry_op; // pass through all customizations except set_error, which retries the operation. template struct _retry_receiver - : exec::receiver_adaptor<_retry_receiver> { - _op* o_; + : stdexec::receiver_adaptor<_retry_receiver> { + _retry_op* o_; - R&& base() && noexcept { return (R&&) o_->r_; } + R&& base() && noexcept { return std::move(o_->r_); } const R& base() const & noexcept { return o_->r_; } - explicit _retry_receiver(_op* o) : o_(o) {} + explicit _retry_receiver(_retry_op* o) : o_(o) {} void set_error(auto&&) && noexcept { o_->_retry(); // This causes the op to be retried @@ -629,97 +771,121 @@ struct _retry_receiver // Hold the nested operation state in an optional so we can // re-construct and re-start it if the operation fails. template -struct _op { +struct _retry_op { + using _child_op_t = + stdexec::connect_result_t>; + S s_; R r_; - optional< - exec::connect_result_t>> o_; + optional<_child_op_t> o_; - _op(S s, R r): s_((S&&)s), r_((R&&)r), o_{_connect()} {} _op(_op&&) = delete; + _op(S s, R r) + : s_(std::move(s)), r_(std::move(r)), o_{_connect()} {} auto _connect() noexcept { return _conv{[this] { - return exec::connect(s_, _retry_receiver{this}); + return stdexec::connect(s_, _retry_receiver{this}); }}; } - void _retry() noexcept try { - o_.emplace(_connect()); // potentially-throwing - exec::start(*o_); - } catch(...) { - exec::set_error((R&&) r_, std::current_exception()); + + void _retry() noexcept { + try { + o_.emplace(_connect()); // potentially-throwing + stdexec::start(*o_); + } catch(...) { + stdexec::set_error(std::move(r_), std::current_exception()); + } } - friend void tag_invoke(exec::start_t, _op& o) noexcept { - exec::start(*o.o_); + + void start() & noexcept { + stdexec::start(*o_); } }; +// Helpers for computing the `then` sender's completion signatures: +template + using _value_t = + stdexec::completion_signatures; + +template + using _error_t = stdexec::completion_signatures<>; + +using _except_sig = + stdexec::completion_signatures; + template struct _retry_sender { - using sender_concept = exec::sender_t; + using sender_concept = stdexec::sender_t; S s_; - explicit _retry_sender(S s) : s_((S&&) s) {} - - template - using _value_t = - exec::completion_signatures; - template - using _error_t = exec::completion_signatures<>; + explicit _retry_sender(S s) : s_(std::move(s)) {} // Declare the signatures with which this sender can complete template - friend auto tag_invoke(exec::get_completion_signatures_t, const _retry_sender&, Env) - -> exec::transform_completion_signatures_of, - _value_t, _error_t>; - - template - friend _op tag_invoke(exec::connect_t, _retry_sender&& self, R r) { - return {(S&&) self.s_, (R&&) r}; + using _compl_sigs = + stdexec::transform_completion_signatures_of< + S&, Env, _except_sig, _value_t, _error_t>; + + template + auto get_completion_signatures(Env&&) const noexcept -> _compl_sigs { + return {}; } - friend decltype(auto) tag_invoke(exec::get_env_t, const _retry_sender& self) noexcept { - return get_env(self.s_); + template + requires stdexec::sender_to> + _retry_op connect(R r) && { + return {std::move(s_), std::move(r)}; + } + + decltype(auto) get_env() const noexcept { + return get_env(s_); } }; -template -exec::sender auto retry(S s) { - return _retry_sender{(S&&) s}; +template +stdexec::sender auto retry(S s) { + return _retry_sender{std::move(s)}; } ``` -The `retry` algorithm takes a multi-shot sender and causes it to repeat on error, passing -through values and stopped signals. Each time the input sender is restarted, a new receiver -is connected and the resulting operation state is stored in an `optional`, which allows us -to reinitialize it multiple times. +The `retry` algorithm takes a multi-shot sender and causes it to repeat on +error, passing through values and stopped signals. Each time the input sender is +restarted, a new receiver is connected and the resulting operation state is +stored in an `optional`, which allows us to reinitialize it multiple times. This example does the following: -1. Defines a `_conv` utility that takes advantage of C++17's guaranteed copy elision to - emplace a non-movable type in a `std::optional`. +1. Defines a `_conv` utility that takes advantage of C++17's guaranteed copy + elision to emplace a non-movable type in a `std::optional`. -2. Defines a `_retry_receiver` that holds a pointer back to the operation state. It passes - all customizations through unmodified to the inner receiver owned by the operation state - except for `set_error`, which causes a `_retry()` function to be called instead. +2. Defines a `_retry_receiver` that holds a pointer back to the operation state. + It passes all customizations through unmodified to the inner receiver owned + by the operation state except for `set_error`, which causes a `_retry()` + function to be called instead. -3. Defines an operation state that aggregates the input sender and receiver, and declares - storage for the nested operation state in an `optional`. Constructing the operation - state constructs a `_retry_receiver` with a pointer to the (under construction) operation - state and uses it to connect to the aggregated sender. +3. Defines an operation state that aggregates the input sender and receiver, and + declares storage for the nested operation state in an `optional`. + Constructing the operation state constructs a `_retry_receiver` with a + pointer to the (under construction) operation state and uses it to connect + to the input sender. -4. Starting the operation state dispatches to `start` on the inner operation state. +4. Starting the operation state dispatches to `start` on the inner operation + state. -5. The `_retry()` function reinitializes the inner operation state by connecting the sender - to a new receiver, holding a pointer back to the outer operation state as before. +5. The `_retry()` function reinitializes the inner operation state by connecting + the sender to a new receiver, holding a pointer back to the outer operation + state as before. -6. After reinitializing the inner operation state, `_retry()` calls `start` on it, causing - the failed operation to be rescheduled. +6. After reinitializing the inner operation state, `_retry()` calls `start` on + it, causing the failed operation to be rescheduled. -7. Defines a `_retry_sender` that implements the `connect` customization point to return - an operation state constructed from the passed-in sender and receiver. +7. Defines a `_retry_sender` that implements a `connect` member function to + return an operation state constructed from the passed-in sender and + receiver. -8. `_retry_sender` also implements the `get_completion_signatures` customization point to describe the ways this sender may complete when executed in a particular execution resource. +8. `_retry_sender` also implements a `get_completion_signatures` member function + to describe the ways this sender may complete when executed in a particular + execution resource. ## Examples: Schedulers ## {#example-schedulers} @@ -728,58 +894,59 @@ In this section we look at some schedulers of varying complexity. ### Inline scheduler ### {#example-schedulers-inline} ```c++ +namespace stdexec = std::execution; + class inline_scheduler { template - struct _op { - [[no_unique_address]] R rec_; - friend void tag_invoke(std::execution::start_t, _op& op) noexcept { - std::execution::set_value((R&&) op.rec_); - } - }; + struct _op { + R rec_; + void start() & noexcept { + stdexec::set_value(std::move(rec_)); + } + }; struct _env { template - friend inline_scheduler tag_invoke( - std::execution::get_completion_scheduler_t, _env) noexcept { - return {}; - } + inline_scheduler query(stdexec::get_completion_scheduler_t) const noexcept { + return {}; + } }; struct _sender { - using sender_concept = std::execution::sender_t; - using completion_signatures = - std::execution::completion_signatures; - - template - friend auto tag_invoke(std::execution::connect_t, _sender, R&& rec) - noexcept(std::is_nothrow_constructible_v, R>) - -> _op> { - return {(R&&) rec}; - } + using sender_concept = stdexec::sender_t; + using _compl_sigs = stdexec::completion_signatures; + using completion_signatures = _compl_sigs; + + template R> + _op connect(R rec) noexcept(std::is_nothrow_move_constructible_v) { + return {std::move(rec)}; + } - friend _env tag_invoke(exec::get_env_t, _sender) noexcept { + _env get_env() const noexcept { return {}; } }; - friend _sender tag_invoke(std::execution::schedule_t, const inline_scheduler&) noexcept { + public: + inline_scheduler() = default; + + _sender schedule() const noexcept { return {}; } - public: - inline_scheduler() = default; bool operator==(const inline_scheduler&) const noexcept = default; }; ``` -The inline scheduler is a trivial scheduler that completes immediately and synchronously on -the thread that calls `std::execution::start` on the operation state produced by its sender. -In other words, start(connect(schedule(inline-scheduler), receiver)) is -just a fancy way of saying `set_value(receiver)`, with the exception of the fact that `start` -wants to be passed an lvalue. +The inline scheduler is a trivial scheduler that completes immediately and +synchronously on the thread that calls `std::execution::start` on the operation +state produced by its sender. In other words, +`start(connect(schedule(inline_scheduler()), receiver))` is just a fancy way of +saying `set_value(receiver)`, with the exception of the fact that `start` wants +to be passed an lvalue. -Although not a particularly useful scheduler, it serves to illustrate the basics of -implementing one. The `inline_scheduler`: +Although not a particularly useful scheduler, it serves to illustrate the basics +of implementing one. The `inline_scheduler`: 1. Customizes `execution::schedule` to return an instance of the sender type `_sender`. @@ -796,8 +963,9 @@ implementing one. The `inline_scheduler`: ### Single thread scheduler ### {#example-single-thread} -This example shows how to create a scheduler for an execution resource that consists of a single -thread. It is implemented in terms of a lower-level execution resource called `std::execution::run_loop`. +This example shows how to create a scheduler for an execution resource that +consists of a single thread. It is implemented in terms of a lower-level +execution resource called `std::execution::run_loop`. ```c++ class single_thread_context { @@ -809,6 +977,7 @@ public: : loop_() , thread_([this] { loop_.run(); }) {} + single_thread_context(single_thread_context&&) = delete; ~single_thread_context() { loop_.finish(); @@ -825,12 +994,13 @@ public: }; ``` -The `single_thread_context` owns an event loop and a thread to drive it. In the destructor, it tells the event -loop to finish up what it's doing and then joins the thread, blocking for the event loop to drain. +The `single_thread_context` owns an event loop and a thread to drive it. In the +destructor, it tells the event loop to finish up what it's doing and then joins +the thread, blocking for the event loop to drain. The interesting bits are in the `execution::run_loop` context implementation. It is slightly too long to include here, so we only provide [a reference to -it](https://github.com/NVIDIA/stdexec/blob/c2cdb2a2abe2b29a34cf277728319d6ca92ec0bb/include/stdexec/execution.hpp#L3916-L4101), +it](https://github.com/NVIDIA/stdexec/blob/596707991a321ecf8219c03b79819ff4e8ecd278/include/stdexec/execution.hpp#L4201-L4339), but there is one noteworthy detail about its implementation: It uses space in its operation states to build an intrusive linked list of work items. In structured concurrency patterns, the operation states of nested operations @@ -841,7 +1011,10 @@ allocations. ## Examples: Server theme ## {#example-server} -In this section we look at some examples of how one would use senders to implement an HTTP server. The examples ignore the low-level details of the HTTP server and looks at how senders can be combined to achieve the goals of the project. +In this section we look at some examples of how one would use senders to +implement an HTTP server. The examples ignore the low-level details of the HTTP +server and looks at how senders can be combined to achieve the goals of the +project. General application context: * server application that processes images @@ -856,77 +1029,97 @@ General application context: ### Composability with `execution::let_*` ### {#example-server-let} Example context: -- we are looking at the flow of processing an HTTP request and sending back the response -- show how one can break the (slightly complex) flow into steps with `execution::let_*` functions -- different phases of processing HTTP requests are broken down into separate concerns -- each part of the processing might use different execution resources (details not shown in this example) -- error handling is generic, regardless which component fails; we always send the right response to the clients +- we are looking at the flow of processing an HTTP request and sending back the + response. +- show how one can break the (slightly complex) flow into steps with + `execution::let_*` functions. +- different phases of processing HTTP requests are broken down into separate + concerns. +- each part of the processing might use different execution resources (details + not shown in this example). +- error handling is generic, regardless which component fails; we always send + the right response to the clients. Goals: -- show how one can break more complex flows into steps with let_* functions -- exemplify the use of `let_value`, `let_error`, `let_stopped`, and `just` algorithms +- show how one can break more complex flows into steps with let_* functions. +- exemplify the use of `let_value`, `let_error`, `let_stopped`, and `just` + algorithms. ```c++ -namespace ex = std::execution; +namespace stdexec = std::execution; // Returns a sender that yields an http_request object for an incoming request -ex::sender auto schedule_request_start(read_requests_ctx ctx) {...} +stdexec::sender auto schedule_request_start(read_requests_ctx ctx) {...} + // Sends a response back to the client; yields a void signal on success -ex::sender auto send_response(const http_response& resp) {...} +stdexec::sender auto send_response(const http_response& resp) {...} + // Validate that the HTTP request is well-formed; forwards the request on success -ex::sender auto validate_request(const http_request& req) {...} +stdexec::sender auto validate_request(const http_request& req) {...} // Handle the request; main application logic -ex::sender auto handle_request(const http_request& req) { +stdexec::sender auto handle_request(const http_request& req) { //... - return ex::just(http_response{200, result_body}); + return stdexec::just(http_response{200, result_body}); } // Transforms server errors into responses to be sent to the client -ex::sender auto error_to_response(std::exception_ptr err) { +stdexec::sender auto error_to_response(std::exception_ptr err) { try { std::rethrow_exception(err); } catch (const std::invalid_argument& e) { - return ex::just(http_response{404, e.what()}); + return stdexec::just(http_response{404, e.what()}); } catch (const std::exception& e) { - return ex::just(http_response{500, e.what()}); + return stdexec::just(http_response{500, e.what()}); } catch (...) { - return ex::just(http_response{500, "Unknown server error"}); + return stdexec::just(http_response{500, "Unknown server error"}); } } + // Transforms cancellation of the server into responses to be sent to the client -ex::sender auto stopped_to_response() { - return ex::just(http_response{503, "Service temporarily unavailable"}); +stdexec::sender auto stopped_to_response() { + return stdexec::just(http_response{503, "Service temporarily unavailable"}); } + //... + // The whole flow for transforming incoming requests into responses -ex::sender auto snd = +stdexec::sender auto snd = // get a sender when a new request comes schedule_request_start(the_read_requests_ctx) // make sure the request is valid; throw if not - | ex::let_value(validate_request) + | stdexec::let_value(validate_request) // process the request in a function that may be using a different execution resource - | ex::let_value(handle_request) + | stdexec::let_value(handle_request) // If there are errors transform them into proper responses - | ex::let_error(error_to_response) + | stdexec::let_error(error_to_response) // If the flow is cancelled, send back a proper response - | ex::let_stopped(stopped_to_response) + | stdexec::let_stopped(stopped_to_response) // write the result back to the client - | ex::let_value(send_response) + | stdexec::let_value(send_response) // done ; + // execute the whole flow asynchronously -ex::start_detached(std::move(snd)); +stdexec::start_detached(std::move(snd)); ``` -The example shows how one can separate out the concerns for interpreting requests, validating requests, running the main logic for handling the request, generating error responses, handling cancellation and sending the response back to the client. -They are all different phases in the application, and can be joined together with the `let_*` functions. +The example shows how one can separate out the concerns for interpreting +requests, validating requests, running the main logic for handling the request, +generating error responses, handling cancellation and sending the response back +to the client. They are all different phases in the application, and can be +joined together with the `let_*` functions. -All our functions return `execution::sender` objects, so that they can all generate success, failure and cancellation paths. -For example, regardless where an error is generated (reading request, validating request or handling the response), we would have one common block to handle the error, and following error flows is easy. +All our functions return `execution::sender` objects, so that they can all +generate success, failure and cancellation paths. For example, regardless where +an error is generated (reading request, validating request or handling the +response), we would have one common block to handle the error, and following +error flows is easy. -Also, because of using `execution::sender` objects at any step, we might expect any of these steps to be completely asynchronous; the overall flow doesn't care. -Regardless of the execution resource in which the steps, or part of the steps are executed in, the flow is still the same. +Also, because of using `execution::sender` objects at any step, we might expect +any of these steps to be completely asynchronous; the overall flow doesn't care. +Regardless of the execution resource in which the steps, or part of the steps +are executed in, the flow is still the same. ### Moving between execution resources with `execution::on` and `execution::transfer` ### {#example-server-on} @@ -939,53 +1132,54 @@ Goals: - show how one can change the execution resource - exemplify the use of `on` and `transfer` algorithms - ```c++ -namespace ex = std::execution; +namespace stdexec = std::execution; -size_t legacy_read_from_socket(int sock, char* buffer, size_t buffer_len) {} -void process_read_data(const char* read_data, size_t read_len) {} +size_t legacy_read_from_socket(int sock, char* buffer, size_t buffer_len); +void process_read_data(const char* read_data, size_t read_len); //... // A sender that just calls the legacy read function -auto snd_read = ex::just(sock, buf, buf_len) | ex::then(legacy_read_from_socket); +auto snd_read = stdexec::just(sock, buf, buf_len) + | stdexec::then(legacy_read_from_socket); + // The entire flow auto snd = // start by reading data on the I/O thread - ex::on(io_sched, std::move(snd_read)) + stdexec::on(io_sched, std::move(snd_read)) // do the processing on the worker threads pool - | ex::transfer(work_sched) + | stdexec::transfer(work_sched) // process the incoming data (on worker threads) - | ex::then([buf](int read_len) { process_read_data(buf, read_len); }) + | stdexec::then([buf](int read_len) { process_read_data(buf, read_len); }) // done ; + // execute the whole flow asynchronously -ex::start_detached(std::move(snd)); +stdexec::start_detached(std::move(snd)); ``` -The example assume that we need to wrap some legacy code of reading sockets, and handle execution resource switching. -(This style of reading from socket may not be the most efficient one, but it's working for our purposes.) -For performance reasons, the reading from the socket needs to be done on the I/O thread, and all the processing needs to happen on a work-specific execution resource (i.e., thread pool). - -Calling `execution::on` will ensure that the given sender will be started on the given scheduler. -In our example, `snd_read` is going to be started on the I/O scheduler. -This sender will just call the legacy code. - -The completion-signal will be issued in the I/O execution resource, so we have to move it to the work thread pool. -This is achieved with the help of the `execution::transfer` algorithm. -The rest of the processing (in our case, the last call to `then`) will happen in the work thread pool. - -The reader should notice the difference between `execution::on` and `execution::transfer`. -The `execution::on` algorithm will ensure that the given sender will start in the specified context, and doesn't care where the completion-signal for that sender is sent. -The `execution::transfer` algorithm will not care where the given sender is going to be started, but will ensure that the completion-signal of will be transferred to the given context. - -## What this proposal is **not** ## {#intro-is-not} - -This paper is not a patch on top of [[P0443R14]]; we are not asking to update the existing paper, we are asking to retire it in favor of this paper, which is already self-contained; any example code within this paper can be written in Standard C++, without the need -to standardize any further facilities. - -This paper is not an alternative design to [[P0443R14]]; rather, we have taken the design in the current executors paper, and applied targeted fixes to allow it to fulfill the promises of the sender/receiver model, as well as provide all the facilities we consider -essential when writing user code using standard execution concepts; we have also applied the guidance of removing one-way executors from the paper entirely, and instead provided an algorithm based around senders that serves the same purpose. +The example assume that we need to wrap some legacy code of reading sockets, and +handle execution resource switching. (This style of reading from socket may not +be the most efficient one, but it's working for our purposes.) For performance +reasons, the reading from the socket needs to be done on the I/O thread, and all +the processing needs to happen on a work-specific execution resource (i.e., +thread pool). + +Calling `execution::on` will ensure that the given sender will be started on the +given scheduler. In our example, `snd_read` is going to be started on the I/O +scheduler. This sender will just call the legacy code. + +The completion-signal will be issued in the I/O execution resource, so we have +to move it to the work thread pool. This is achieved with the help of the +`execution::transfer` algorithm. The rest of the processing (in our case, the +last call to `then`) will happen in the work thread pool. + +The reader should notice the difference between `execution::on` and +`execution::transfer`. The `execution::on` algorithm will ensure that the given +sender will start in the specified context, and doesn't care where the +completion-signal for that sender is sent. The `execution::transfer` algorithm +will not care where the given sender is going to be started, but will ensure +that the completion-signal of will be transferred to the given context. ## Design changes from P0443 ## {#intro-compare} @@ -1022,112 +1216,254 @@ essential when writing user code using standard execution concepts; we have also ## Prior art ## {#intro-prior-art} -This proposal builds upon and learns from years of prior art with asynchronous and parallel programming frameworks in C++. In this section, we discuss async abstractions that have previously been suggested as a possible basis for asynchronous algorithms and why they fall short. +This proposal builds upon and learns from years of prior art with asynchronous +and parallel programming frameworks in C++. In this section, we discuss async +abstractions that have previously been suggested as a possible basis for +asynchronous algorithms and why they fall short. ### Futures ### {#intro-prior-art-futures} -A future is a handle to work that has already been scheduled for execution. It is one end of a communication channel; the other end is a promise, used to receive the result from the concurrent operation and to communicate it to the future. +A future is a handle to work that has already been scheduled for execution. It +is one end of a communication channel; the other end is a promise, used to +receive the result from the concurrent operation and to communicate it to the +future. -Futures, as traditionally realized, require the dynamic allocation and management of a shared state, synchronization, and typically type-erasure of work and continuation. Many of these costs are inherent in the nature of "future" as a handle to work that is already scheduled for execution. These expenses rule out the future abstraction for many uses and makes it a poor choice for a basis of a generic mechanism. +Futures, as traditionally realized, require the dynamic allocation and +management of a shared state, synchronization, and typically type-erasure of +work and continuation. Many of these costs are inherent in the nature of +"future" as a handle to work that is already scheduled for execution. These +expenses rule out the future abstraction for many uses and makes it a poor +choice for a basis of a generic mechanism. ### Coroutines ### {#intro-prior-art-coroutines} -C++20 coroutines are frequently suggested as a basis for asynchronous algorithms. It's fair to ask why, if we added coroutines to C++, are we suggesting the addition of a library-based abstraction for asynchrony. Certainly, coroutines come with huge syntactic and semantic advantages over the alternatives. - -Although coroutines are lighter weight than futures, coroutines suffer many of the same problems. Since they typically start suspended, they can avoid synchronizing the chaining of dependent work. However in many cases, coroutine frames require an unavoidable dynamic allocation and indirect function calls. This is done to hide the layout of the coroutine frame from the C++ type system, which in turn makes possible the separate compilation of coroutines and certain compiler optimizations, such as optimization of the coroutine frame size. - -Those advantages come at a cost, though. Because of the dynamic allocation of coroutine frames, coroutines in embedded or heterogeneous environments, which often lack support for dynamic allocation, require great attention to detail. And the allocations and indirections tend to complicate the job of the inliner, often resulting in sub-optimal codegen. - -The coroutine language feature mitigates these shortcomings somewhat with the HALO optimization [[P0981R0]], which leverages existing compiler optimizations such as allocation elision and devirtualization to inline the coroutine, completely eliminating the runtime overhead. However, HALO requires a sophisiticated compiler, and a fair number of stars need to align for the optimization to kick in. In our experience, more often than not in real-world code today's compilers are not able to inline the coroutine, resulting in allocations and indirections in the generated code. - -In a suite of generic async algorithms that are expected to be callable from hot code paths, the extra allocations and indirections are a deal-breaker. It is for these reasons that we consider coroutines a poor choise for a basis of all standard async. +C++20 coroutines are frequently suggested as a basis for asynchronous +algorithms. It's fair to ask why, if we added coroutines to C++, are we +suggesting the addition of a library-based abstraction for asynchrony. +Certainly, coroutines come with huge syntactic and semantic advantages over the +alternatives. + +Although coroutines are lighter weight than futures, coroutines suffer many of +the same problems. Since they typically start suspended, they can avoid +synchronizing the chaining of dependent work. However in many cases, coroutine +frames require an unavoidable dynamic allocation and indirect function calls. +This is done to hide the layout of the coroutine frame from the C++ type system, +which in turn makes possible the separate compilation of coroutines and certain +compiler optimizations, such as optimization of the coroutine frame size. + +Those advantages come at a cost, though. Because of the dynamic allocation of +coroutine frames, coroutines in embedded or heterogeneous environments, which +often lack support for dynamic allocation, require great attention to detail. +And the allocations and indirections tend to complicate the job of the inliner, +often resulting in sub-optimal codegen. + +The coroutine language feature mitigates these shortcomings somewhat with the +HALO optimization [[P0981R0]], which leverages existing compiler optimizations +such as allocation elision and devirtualization to inline the coroutine, +completely eliminating the runtime overhead. However, HALO requires a +sophisiticated compiler, and a fair number of stars need to align for the +optimization to kick in. In our experience, more often than not in real-world +code today's compilers are not able to inline the coroutine, resulting in +allocations and indirections in the generated code. + +In a suite of generic async algorithms that are expected to be callable from hot +code paths, the extra allocations and indirections are a deal-breaker. It is for +these reasons that we consider coroutines a poor choise for a basis of all +standard async. ### Callbacks ### {#intro-prior-art-callbacks} -Callbacks are the oldest, simplest, most powerful, and most efficient mechanism for creating chains of work, but suffer problems of their own. Callbacks must propagate either errors or values. This simple requirement yields many different interface possibilities. The lack of a standard callback shape obstructs generic design. +Callbacks are the oldest, simplest, most powerful, and most efficient mechanism +for creating chains of work, but suffer problems of their own. Callbacks must +propagate either errors or values. This simple requirement yields many different +interface possibilities. The lack of a standard callback shape obstructs generic +design. -Additionally, few of these possibilities accommodate cancellation signals when the user requests upstream work to stop and clean up. +Additionally, few of these possibilities accommodate cancellation signals when +the user requests upstream work to stop and clean up. ## Field experience ## {#intro-field-experience} ### libunifex ### {#intro-field-experience-libunifex} -This proposal draws heavily from our field experience with [libunifex](https://github.com/facebookexperimental/libunifex). Libunifex implements all of the concepts and customization points defined in this paper (with slight variations -- the design of P2300 has evolved due to LEWG feedback), many of this paper's algorithms (some under different names), and much more besides. - -Libunifex has several concrete schedulers in addition to the `run_loop` suggested here (where it is called `manual_event_loop`). It has schedulers that dispatch efficiently to epoll and io_uring on Linux and the Windows Thread Pool on Windows. +This proposal draws heavily from our field experience with +[libunifex](https://github.com/facebookexperimental/libunifex). Libunifex +implements all of the concepts and customization points defined in this paper +(with slight variations -- the design of P2300 has evolved due to LEWG +feedback), many of this paper's algorithms (some under different names), and +much more besides. + +Libunifex has several concrete schedulers in addition to the `run_loop` +suggested here (where it is called `manual_event_loop`). It has schedulers that +dispatch efficiently to epoll and io_uring on Linux and the Windows Thread Pool +on Windows. + +In addition to the proposed interfaces and the additional schedulers, it has +several important extensions to the facilities described in this paper, which +demonstrate directions in which these abstractions may be evolved over time, +including: + +* Timed schedulers, which permit scheduling work on an execution resource at a + particular time or after a particular duration has elapsed. In addition, it + provides time-based algorithms. +* File I/O schedulers, which permit filesystem I/O to be scheduled. +* Two complementary abstractions for streams (asynchronous ranges), and a set of + stream-based algorithms. + +Libunifex has seen heavy production use at Meta. An employee summarizes it +as follows: + +> As of June, 2023, Unifex is still used in production at Meta. It's used to +> express the asynchrony in +> [rsys](https://engineering.fb.com/2020/12/21/video-engineering/rsys/), and is +> therefore serving video calling to billions of people every month on Meta's +> social networking apps on iOS, Android, Windows, and macOS. It's also serving +> the Virtual Desktop experience on Oculus Quest devices, and some internal uses +> that run on Linux. +> +> One team at Meta has migrated from `folly::Future` to `unifex::task` and seen +> significant developer efficiency improvements. Coroutines are easier to +> understand than chained futures so the team was able to meet requirements for +> certain constrained environments that would have been too complicated to +> maintain with futures. +> +> In all the cases mentioned above, developers mix-and-match between the sender +> algorithms in Unifex and Unifex's coroutine type, `unifex::task`. We also rely +> on `unifex::task`'s scheduler affinity to minimize surprise when programming +> with coroutines. -In addition to the proposed interfaces and the additional schedulers, it has several important extensions to the facilities described in this paper, which demonstrate directions in which these abstractions may be evolved over time, including: +### stdexec ### {#intro-field-experience-stdexec} -* Timed schedulers, which permit scheduling work on an execution resource at a particular time or after a particular duration has elapsed. In addition, it provides time-based algorithms. -* File I/O schedulers, which permit filesystem I/O to be scheduled. -* Two complementary abstractions for streams (asynchronous ranges), and a set of stream-based algorithms. +[stdexec](https://github.com/NVIDIA/stdexec) is the reference implementation of +this proposal. It is a complete implementation, written from the specification +in this paper, and is current with [\R8](https://wg21.link/P2300R8). -Libunifex has seen heavy production use at Facebook. As of October 2021, it is currently used in production within the following applications and platforms: +The original purpose of stdexec was to help find specification bugs and to +harden the wording of the proposal, but it has since become one of NVIDIA's core +C++ libraries for high-performance computing. In addition to the facilities +proposed in this paper, stdexec has schedulers for CUDA, Intel TBB, and MacOS. +Like libunifex, its scope has also expanded to include a streaming abstraction +and stream algorithms, and time-based schedulers and algorithms. -* Facebook Messenger on iOS, Android, Windows, and macOS -* Instagram on iOS and Android -* Facebook on iOS and Android -* Portal -* An internal Facebook product that runs on Linux +The stdexec project has seen lots of community interest and contributions. At the +time of writing (March, 2024), the GitHub repository has 1.2k stars, 130 forks, +and 50 contributors. -All of these applications are making direct use of the sender/receiver abstraction as presented in this paper. One product (Instagram on iOS) is making use of the sender/coroutine integration as presented. The monthly active users of these products number in the billions. +stdexec is fit for broad use and for ultimate contribution to libc++. ### Other implementations ### {#intro-field-experience-other-implementations} -The authors are aware of a number of other implementations of sender/receiver from this paper. These are presented here in perceived order of maturity and field experience. +The authors are aware of a number of other implementations of sender/receiver +from this paper. These are presented here in perceived order of maturity and +field experience. * [[HPX]] - HPX is a general purpose C++ runtime system for parallel and distributed applications that has been under active development since 2007. HPX exposes a uniform, standards-oriented API, and keeps abreast of the latest standards and proposals. It is used in a wide variety of high-performance applications. + HPX is a general purpose C++ runtime system for parallel and distributed + applications that has been under active development since 2007. HPX exposes + a uniform, standards-oriented API, and keeps abreast of the latest standards + and proposals. It is used in a wide variety of high-performance + applications. - The sender/receiver implementation in HPX has been under active development since May 2020. It is used to erase the overhead of futures and to make it possible to write efficient generic asynchronous algorithms that are agnostic to their execution resource. In HPX, algorithms can migrate execution between execution resources, even to GPUs and back, using a uniform standard interface with sender/receiver. + The sender/receiver implementation in HPX has been under active development + since May 2020. It is used to erase the overhead of futures and to make it + possible to write efficient generic asynchronous algorithms that are + agnostic to their execution resource. In HPX, algorithms can migrate + execution between execution resources, even to GPUs and back, using a + uniform standard interface with sender/receiver. - Far and away, the HPX team has the greatest usage experience outside Facebook. Mikael Simberg summarizes the experience as follows: + Far and away, the HPX team has the greatest usage experience outside + Facebook. Mikael Simberg summarizes the experience as follows: - > Summarizing, for us the major benefits of sender/receiver compared to the old model are: + > Summarizing, for us the major benefits of sender/receiver compared to the + > old model are: > > 1. Proper hooks for transitioning between execution resources. > 2. The adaptors. Things like `let_value` are really nice additions. - > 3. Separation of the error channel from the value channel (also cancellation, but we don't have much use for it at the moment). Even from a teaching perspective having to explain that the future `f2` in the continuation will always be ready here `f1.then([](future f2) {...})` is enough of a reason to separate the channels. All the other obvious reasons apply as well of course. - > 4. For futures we have a thing called `hpx::dataflow` which is an optimized version of `when_all(...).then(...)` which avoids intermediate allocations. With the sender/receiver `when_all(...) | then(...)` we get that "for free". + > 3. Separation of the error channel from the value channel (also + > cancellation, but we don't have much use for it at the moment). Even + > from a teaching perspective having to explain that the future `f2` in + > the continuation will always be ready here `f1.then([](future f2) + > {...})` is enough of a reason to separate the channels. All the other + > obvious reasons apply as well of course. + > 4. For futures we have a thing called `hpx::dataflow` which is an + > optimized version of `when_all(...).then(...)` which avoids + > intermediate allocations. With the sender/receiver `when_all(...) | + > then(...)` we get that "for free". * [kuhllib](https://github.com/dietmarkuehl/kuhllib/) by Dietmar Kuehl - This is a prototype Standard Template Library with an implementation of sender/receiver that has been under development since May, 2021. It is significant mostly for its support for sender/receiver-based networking interfaces. + This is a prototype Standard Template Library with an implementation of + sender/receiver that has been under development since May, 2021. It is + significant mostly for its support for sender/receiver-based networking + interfaces. - Here, Dietmar Kuehl speaks about the perceived complexity of sender/receiver: + Here, Dietmar Kuehl speaks about the perceived complexity of + sender/receiver: - > ... and, also similar to STL: as I had tried to do things in that space before I recognize sender/receivers as being maybe complicated in one way but a huge simplification in another one: like with STL I think those who use it will benefit - if not from the algorithm from the clarity of abstraction: the separation of concerns of STL (the algorithm being detached from the details of the sequence representation) is a major leap. Here it is rather similar: the separation of the asynchronous algorithm from the details of execution. Sure, there is some glue to tie things back together but each of them is simpler than the combined result. + > ... and, also similar to STL: as I had tried to do things in that space + > before I recognize sender/receivers as being maybe complicated in one way + > but a huge simplification in another one: like with STL I think those who + > use it will benefit - if not from the algorithm from the clarity of + > abstraction: the separation of concerns of STL (the algorithm being + > detached from the details of the sequence representation) is a major leap. + > Here it is rather similar: the separation of the asynchronous algorithm + > from the details of execution. Sure, there is some glue to tie things back + > together but each of them is simpler than the combined result. Elsewhere, he said: - > ... to me it feels like sender/receivers are like iterators when STL emerged: they are different from what everybody did in that space. However, everything people are already doing in that space isn’t right. - - Kuehl also has experience teaching sender/receiver at Bloomberg. About that experience he says: - - > When I asked [my students] specifically about how complex they consider the sender/receiver stuff the feedback was quite unanimous that the sender/receiver parts aren’t trivial but not what contributes to the complexity. - -* [The reference implementation](https://github.com/NVIDIA/stdexec) + > ... to me it feels like sender/receivers are like iterators when STL + > emerged: they are different from what everybody did in that space. + > However, everything people are already doing in that space isn't right. - This is a complete implementation written from the specification in this paper. Its primary purpose is to help find specification bugs and to harden the wording of the proposal. It is - fit for broad use and for contribution to libc++. + Kuehl also has experience teaching sender/receiver at Bloomberg. About that + experience he says: - It is current with R8 of this paper. + > When I asked [my students] specifically about how complex they consider + > the sender/receiver stuff the feedback was quite unanimous that the + > sender/receiver parts aren't trivial but not what contributes to the + > complexity. -* [Reference implementation for the Microsoft STL](https://github.com/miscco/STL/tree/proposal/executors) by Michael Schellenberger Costa +* [C++ Bare Metal Senders and Receivers](https://github.com/intel/cpp-baremetal-senders-and-receivers) from Intel - This is another reference implementation of this proposal, this time in a fork of the Mircosoft STL implementation. Michael Schellenberger Costa is not affiliated with Microsoft. He intends to contribute this implementation upstream when it is complete. + This is a prototype implementation of sender/receiver by Intel that has been + under development since August, 2023. It is significant mostly for its + support for bare metal (no operating system) and embedded systems, a domain + for which senders are particularly well-suited due to their very low dynamic + memory requirements. ### Inspirations ### {#intro-field-experience-inspirations} -This proposal also draws heavily from our experience with [Thrust](https://github.com/NVIDIA/thrust) and [Agency](https://github.com/agency-library/agency). It is also inspired by the needs of countless other C++ frameworks for asynchrony, parallelism, and concurrency, including: +This proposal also draws heavily from our experience with +[Thrust](https://github.com/NVIDIA/thrust) and +[Agency](https://github.com/agency-library/agency). It is also inspired by the +needs of countless other C++ frameworks for asynchrony, parallelism, and +concurrency, including: -* HPX +* \[HPX](https://github.com/STEllAR-GROUP/hpx) * [Folly](https://github.com/facebook/folly/blob/master/folly/docs/Futures.md) * [stlab](https://stlab.cc/libraries/concurrency/) # Revision history # {#revisions} +## R9 ## {#r9} + +The changes since R8 are as follows: + +Fixes: + + * The `tag_invoke` mechanism has been replace with member functions + for customizations as per \[P2855](https://wg21.link/p2855). + + * The removal of `tag_invoke` necessitated a respecification of the + `receiver_adaptor` utility. + +Enhancements: + + * The specification of the `sync_wait` algorithm has been updated + for clarity. + ## R8 ## {#r8} The changes since R7 are as follows: @@ -1228,8 +1564,9 @@ The changes since R5 are as follows: are no longer needed and are dropped. * `ensure_started` and `split` are changed to persist the result of calling `get_attrs()` on the input sender. - * Reorder constraints of the `scheduler` and `receiver` concepts to avoid constraint recursion - when used in tandem with poorly-constrained, implicitly convertible types. + * Reorder constraints of the `scheduler` and `receiver` concepts to avoid + constraint recursion when used in tandem with poorly-constrained, implicitly + convertible types. * Re-express the `sender_of` concept to be more ergonomic and general. * Make the specification of the alias templates `value_types_of_t` and `error_types_of_t`, and the variable template `sends_done` more concise by @@ -1415,11 +1752,12 @@ environment entirely, passing then as separate arguments along with the sender t **Impact:** -This change, apart from increasing the expressive power of the sender/receiver abstraction, has the following impact: +This change, apart from increasing the expressive power of the sender/receiver +abstraction, has the following impact: * Typed senders become moderately more challenging to write. (The new - `completion_signatures` and `transform_completion_signatures` utilities are added - to ease this extra burden.) + `completion_signatures` and `transform_completion_signatures` utilities are + added to ease this extra burden.) * Sender adaptor algorithms that previously constrained their sender arguments to satisfy the `typed_sender` concept can no longer do so as the receiver is @@ -1433,14 +1771,21 @@ This change, apart from increasing the expressive power of the sender/receiver a **"Has it been implemented?"** Yes, the reference implementation, which can be found at -https://github.com/NVIDIA/stdexec, has implemented this -design as well as some dependently-typed senders to confirm that it works. +[https://github.com/NVIDIA/stdexec](https://github.com/NVIDIA/stdexec), has +implemented this design as well as some dependently-typed senders to confirm +that it works. **Implementation experience** -Although this change has not yet been made in libunifex, the most widely adopted sender/receiver implementation, a similar design can be found in Folly's coroutine support library. In Folly.Coro, it is possible to await a special awaitable to obtain the current coroutine's associated scheduler (called an executor in Folly). +Although this change has not yet been made in libunifex, the most widely adopted +sender/receiver implementation, a similar design can be found in Folly's +coroutine support library. In Folly.Coro, it is possible to await a special +awaitable to obtain the current coroutine's associated scheduler (called an +executor in Folly). -For instance, the following Folly code grabs the current executor, schedules a task for execution on that executor, and starts the resulting (scheduled) task by enqueueing it for execution. +For instance, the following Folly code grabs the current executor, schedules a +task for execution on that executor, and starts the resulting (scheduled) task +by enqueueing it for execution. ```c++ // From Facebook's Folly open source library: @@ -1486,19 +1831,20 @@ R4: * Receiver queries have been moved from the receiver into a separate environment object. * Receivers have an associated environment. The new `get_env` CPO retrieves a - receiver's environment. If a receiver doesn't implement `get_env`, it returns - an unspecified "empty" environment -- an empty struct. + receiver's environment. If a receiver doesn't implement `get_env`, it + returns an unspecified "empty" environment -- an empty struct. * `sender_traits` now takes an optional `Env` parameter that is used to determine the error/value types. -* The primary `sender_traits` template is replaced with a `completion_signatures_of_t` - alias implemented in terms of a new `get_completion_signatures` CPO that dispatches - with `tag_invoke`. `get_completion_signatures` takes a sender and an optional - environment. A sender can customize this to specify its value/error types. +* The primary `sender_traits` template is replaced with a + `completion_signatures_of_t` alias implemented in terms of a new + `get_completion_signatures` CPO that dispatches with `tag_invoke`. + `get_completion_signatures` takes a sender and an optional environment. A + sender can customize this to specify its value/error types. * Support for untyped senders is dropped. The `typed_sender` concept has been renamed to `sender` and now takes an optional environment. -* The environment argument to the `sender` concept and the `get_completion_signatures` - CPO defaults to `no_env`. All environment queries fail (are ill-formed) when - passed an instance of `no_env`. +* The environment argument to the `sender` concept and the + `get_completion_signatures` CPO defaults to `no_env`. All environment + queries fail (are ill-formed) when passed an instance of `no_env`. * A type `S` is required to satisfy sender<S> to be considered a sender. If it doesn't know what types it will complete with independent of an environment, it returns an instance of the placeholder @@ -1516,40 +1862,50 @@ The changes since R2 are as follows: Fixes: - * Fix specification of the `on` algorithm to clarify lifetimes of - intermediate operation states and properly scope the `get_scheduler` query. - * Fix a memory safety bug in the implementation of connect-awaitable. - * Fix recursive definition of the `scheduler` concept. +* Fix specification of the `on` algorithm to clarify lifetimes of intermediate + operation states and properly scope the `get_scheduler` query. +* Fix a memory safety bug in the implementation of + connect-awaitable. +* Fix recursive definition of the `scheduler` concept. Enhancements: - * Add `run_loop` execution resource. - * Add `receiver_adaptor` utility to simplify writing receivers. - * Require a scheduler's sender to model `sender_of` and provide a completion scheduler. - * Specify the cancellation scope of the `when_all` algorithm. - * Make `as_awaitable` a customization point. - * Change `connect`'s handling of awaitables to consider those types that are awaitable owing to customization of `as_awaitable`. - * Add `value_types_of_t` and `error_types_of_t` alias templates; rename `stop_token_type_t` to `stop_token_of_t`. - * Add a design rationale for the removal of the possibly eager algorithms. - * Expand the section on field experience. +* Add `run_loop` execution resource. +* Add `receiver_adaptor` utility to simplify writing receivers. +* Require a scheduler's sender to model `sender_of` and provide a completion + scheduler. +* Specify the cancellation scope of the `when_all` algorithm. +* Make `as_awaitable` a customization point. +* Change `connect`'s handling of awaitables to consider those types that are + awaitable owing to customization of `as_awaitable`. +* Add `value_types_of_t` and `error_types_of_t` alias templates; rename + `stop_token_type_t` to `stop_token_of_t`. +* Add a design rationale for the removal of the possibly eager algorithms. +* Expand the section on field experience. ## R2 ## {#r2} The changes since R1 are as follows: * Remove the eagerly executing sender algorithms. -* Extend the `execution::connect` customization point and the `sender_traits<>` template to recognize awaitables as `typed_sender`s. -* Add utilities `as_awaitable()` and `with_awaitable_senders<>` so a coroutine type can trivially make senders awaitable with a coroutine. +* Extend the `execution::connect` customization point and the `sender_traits<>` + template to recognize awaitables as `typed_sender`s. +* Add utilities `as_awaitable()` and `with_awaitable_senders<>` so a coroutine + type can trivially make senders awaitable with a coroutine. * Add a section describing the design of the sender/awaitable interactions. -* Add a section describing the design of the cancellation support in sender/receiver. +* Add a section describing the design of the cancellation support in + sender/receiver. * Add a section showing examples of simple sender adaptor algorithms. * Add a section showing examples of simple schedulers. -* Add a few more examples: a sudoku solver, a parallel recursive file copy, and an echo server. +* Add a few more examples: a sudoku solver, a parallel recursive file copy, and + an echo server. * Refined the forward progress guarantees on the `bulk` algorithm. -* Add a section describing how to use a range of senders to represent async sequences. +* Add a section describing how to use a range of senders to represent async + sequences. * Add a section showing how to use senders to represent partial success. * Add sender factories `execution::just_error` and `execution::just_stopped`. -* Add sender adaptors `execution::stopped_as_optional` and `execution::stopped_as_error`. +* Add sender adaptors `execution::stopped_as_optional` and + `execution::stopped_as_error`. * Document more production uses of sender/receiver at scale. * Various fixes of typos and bugs. @@ -1572,30 +1928,30 @@ Initial revision. The following three sections describe the entirety of the proposed design. * [[#design-intro]] describes the conventions used through the rest of the - design sections, as well as an example illustrating how we envision code will - be written using this proposal. + design sections, as well as an example illustrating how we envision code + will be written using this proposal. * [[#design-user]] describes all the functionality from the perspective we intend for users: it describes the various concepts they will interact with, and what their programming model is. * [[#design-implementer]] describes the machinery that allows for that programming model to function, and the information contained there is - necessary for people implementing senders and sender algorithms (including the - standard library ones) - but is not necessary to use senders productively. + necessary for people implementing senders and sender algorithms (including + the standard library ones) - but is not necessary to use senders + productively. ## Conventions ## {#design-conventions} The following conventions are used throughout the design section: - 1. The namespace proposed in this paper is the same as in [[P0443R14]]: - `std::execution`; however, for brevity, the `std::` part of this name is - omitted. When you see `execution::foo`, treat that as - `std::execution::foo`. - 2. Universal references and explicit calls to `std::move`/`std::forward` are - omitted in code samples and signatures for simplicity; assume universal - references and perfect forwarding unless stated otherwise. - 3. None of the names proposed here are names that we are particularly attached - to; consider the names to be reasonable placeholders that can freely be - changed, should the committee want to do so. +1. The namespace proposed in this paper is the same as in [[P0443R14]]: + `std::execution`; however, for brevity, the `std::` part of this name is + omitted. When you see `execution::foo`, treat that as `std::execution::foo`. +2. Universal references and explicit calls to `std::move`/`std::forward` are + omitted in code samples and signatures for simplicity; assume universal + references and perfect forwarding unless stated otherwise. +3. None of the names proposed here are names that we are particularly attached + to; consider the names to be reasonable placeholders that can freely be + changed, should the committee want to do so. ## Queries and algorithms ## {#design-queries-and-algorithms} @@ -1635,9 +1991,9 @@ execution::sender auto snd = execution::schedule(sch); // on the execution resource associated with sch
-Note that a particular scheduler type may provide other kinds of scheduling operations -which are supported by its associated execution resource. It is not limited to scheduling -purely using the `execution::schedule` API. +Note that a particular scheduler type may provide other kinds of scheduling +operations which are supported by its associated execution resource. It is not +limited to scheduling purely using the `execution::schedule` API. Future papers will propose additional scheduler concepts that extend `scheduler` to add other capabilities. For example: @@ -1684,12 +2040,15 @@ this_thread::sync_wait(cont); ## Senders are composable through sender algorithms ## {#design-composable} -Asynchronous programming often departs from traditional code structure and control flow that we are familiar with. -A successful asynchronous framework must provide an intuitive story for composition of asynchronous work: expressing dependencies, passing objects, managing object lifetimes, etc. +Asynchronous programming often departs from traditional code structure and +control flow that we are familiar with. A successful asynchronous framework must +provide an intuitive story for composition of asynchronous work: expressing +dependencies, passing objects, managing object lifetimes, etc. -The true power and utility of senders is in their composability. -With senders, users can describe generic execution pipelines and graphs, and then run them on and across a variety of different schedulers. -Senders are composed using [=sender algorithms=]: +The true power and utility of senders is in their composability. With senders, +users can describe generic execution pipelines and graphs, and then run them on +and across a variety of different schedulers. Senders are composed using +[=sender algorithms=]: * [=sender factories=], algorithms that take no senders and return a sender. * [=sender adaptors=], algorithms that take (and potentially @@ -1699,30 +2058,64 @@ Senders are composed using [=sender algorithms=]: ## Senders can propagate completion schedulers ## {#design-propagation} -One of the goals of executors is to support a diverse set of execution resources, including traditional thread pools, task and fiber frameworks (like HPX and [Legion](https://github.com/StanfordLegion/legion)), and GPUs and other accelerators (managed by runtimes such as CUDA or SYCL). -On many of these systems, not all execution agents are created equal and not all functions can be run on all execution agents. -Having precise control over the execution resource used for any given function call being submitted is important on such systems, and the users of standard execution facilities will expect to be able to express such requirements. - -[[P0443R14]] was not always clear about the place of execution of any given piece of code. -Precise control was present in the two-way execution API present in earlier executor designs, but it has so far been missing from the senders design. There has been a proposal ([[P1897R3]]) to provide a number of sender algorithms that would enforce certain rules on the places of execution -of the work described by a sender, but we have found those sender algorithms to be insufficient for achieving the best performance on all platforms that are of interest to us. The implementation strategies that we are aware of result in one of the following situations: - - 1. trying to submit work to one execution resource (such as a CPU thread pool) from another execution resource (such as a GPU or a task framework), which assumes that all execution agents are as capable as a `std::thread` (which they aren't). - 2. forcibly interleaving two adjacent execution graph nodes that are both executing on one execution resource (such as a GPU) with glue code that runs on another execution resource (such as a CPU), which is prohibitively expensive for some execution resources (such as CUDA or SYCL). - 3. having to customise most or all sender algorithms to support an execution resource, so that you can avoid problems described in 1. and 2, which we believe is impractical and brittle based on months of field experience attempting this in [Agency](https://github.com/agency-library/agency). - -None of these implementation strategies are acceptable for many classes of parallel runtimes, such as task frameworks (like HPX) or accelerator runtimes (like CUDA or SYCL). - -Therefore, in addition to the `on` sender algorithm from [[P1897R3]], we are proposing a way for senders to advertise what scheduler (and by extension what execution resource) they will complete on. -Any given sender may have [=completion schedulers=] for some or all of the signals (value, error, or stopped) it completes with (for more detail on the completion-signals, see [[#design-receivers]]). -When further work is attached to that sender by invoking sender algorithms, that work will also complete on an appropriate completion scheduler. +One of the goals of executors is to support a diverse set of execution +resources, including traditional thread pools, task and fiber frameworks (like +\[HPX](https://github.com/STEllAR-GROUP/hpx) +[Legion](https://github.com/StanfordLegion/legion)), and GPUs and other +accelerators (managed by runtimes such as CUDA or SYCL). On many of these +systems, not all execution agents are created equal and not all functions can be +run on all execution agents. Having precise control over the execution resource +used for any given function call being submitted is important on such systems, +and the users of standard execution facilities will expect to be able to express +such requirements. + +[[P0443R14]] was not always clear about the place of execution of any +given piece of code. Precise control was present in the two-way execution API +present in earlier executor designs, but it has so far been missing from the +senders design. There has been a proposal ([[P1897R3]]) to provide a number of +sender algorithms that would enforce certain rules on the places of execution of +the work described by a sender, but we have found those sender algorithms to be +insufficient for achieving the best performance on all platforms that are of +interest to us. The implementation strategies that we are aware of result in one +of the following situations: + + 1. trying to submit work to one execution resource (such as a CPU thread pool) + from another execution resource (such as a GPU or a task framework), which + assumes that all execution agents are as capable as a `std::thread` (which + they aren't). + 2. forcibly interleaving two adjacent execution graph nodes that are both + executing on one execution resource (such as a GPU) with glue code that + runs on another execution resource (such as a CPU), which is prohibitively + expensive for some execution resources (such as CUDA or SYCL). + 3. having to customise most or all sender algorithms to support an execution + resource, so that you can avoid problems described in 1. and 2, which we + believe is impractical and brittle based on months of field experience + attempting this in [Agency](https://github.com/agency-library/agency). + +None of these implementation strategies are acceptable for many classes of +parallel runtimes, such as task frameworks (like +\[HPX](https://github.com/STEllAR-GROUP/hpx)) or accelerator runtimes (like CUDA +or SYCL). + +Therefore, in addition to the `on` sender algorithm from [[P1897R3]], we are +proposing a way for senders to advertise what scheduler (and by extension what +execution resource) they will complete on. Any given sender may have +[=completion schedulers=] for some or all of the signals (value, error, or +stopped) it completes with (for more detail on the completion-signals, see +[[#design-receivers]]). When further work is attached to that sender by invoking +sender algorithms, that work will also complete on an appropriate completion +scheduler. ### `execution::get_completion_scheduler` ### {#design-sender-query-get_completion_scheduler} -`get_completion_scheduler` is a query that retrieves the completion scheduler for a specific completion-signal from a sender's environment. -For a sender that lacks a completion scheduler query for a given signal, calling `get_completion_scheduler` is ill-formed. -If a sender advertises a completion scheduler for a signal in this way, that sender must ensure that it [=send|sends=] that signal on an execution agent belonging to an execution resource represented by a scheduler returned from this function. -See [[#design-propagation]] for more details. +`get_completion_scheduler` is a query that retrieves the completion scheduler +for a specific completion-signal from a sender's environment. For a sender that +lacks a completion scheduler query for a given signal, calling +`get_completion_scheduler` is ill-formed. If a sender advertises a completion +scheduler for a signal in this way, that sender must ensure that it +[=send|sends=] that signal on an execution agent belonging to an execution +resource represented by a scheduler returned from this function. See +[[#design-propagation]] for more details.
 execution::scheduler auto cpu_sched = new_thread_scheduler{};
@@ -1751,12 +2144,20 @@ execution::scheduler auto completion_sch3 =
 
 ## Execution resource transitions are explicit ## {#design-transitions}
 
-[[P0443R14]] does not contain any mechanisms for performing an execution resource transition. The only sender algorithm that can create a sender that will move execution to a *specific* execution resource is `execution::schedule`, which does not take an input sender.
-That means that there's no way to construct sender chains that traverse different execution resources. This is necessary to fulfill the promise of senders being able to replace two-way executors, which had this capability.
+[[P0443R14]] does not contain any mechanisms for performing an execution
+resource transition. The only sender algorithm that can create a sender that
+will move execution to a *specific* execution resource is `execution::schedule`,
+which does not take an input sender. That means that there's no way to construct
+sender chains that traverse different execution resources. This is necessary to
+fulfill the promise of senders being able to replace two-way executors, which
+had this capability.
 
-We propose that, for senders advertising their [=completion scheduler=], all execution resource transitions must be explicit; running user code anywhere but where they defined it to run must be considered a bug.
+We propose that, for senders advertising their [=completion scheduler=], all
+execution resource transitions must be explicit; running user code
+anywhere but where they defined it to run must be considered a bug.
 
-The `execution::transfer` sender adaptor performs a transition from one execution resource to another:
+The `execution::transfer` sender adaptor performs a transition from one
+execution resource to another:
 
 
 execution::scheduler auto sch1 = ...;
@@ -1801,31 +2202,41 @@ overloads. Multi-shot senders should also define overloads of
 `execution::connect` that accept rvalue-qualified senders to allow the sender to
 be also used in places where only a single-shot sender is required.
 
-If the user of a sender does not require the sender to remain valid after connecting it to a
-receiver then it can pass an rvalue-reference to the sender to the call to `execution::connect`.
-Such usages should be able to accept either single-shot or multi-shot senders.
+If the user of a sender does not require the sender to remain valid after
+connecting it to a receiver then it can pass an rvalue-reference to the sender
+to the call to `execution::connect`. Such usages should be able to accept either
+single-shot or multi-shot senders.
 
-If the caller does wish for the sender to remain valid after the call then it can pass an lvalue-qualified sender
-to the call to `execution::connect`. Such usages will only accept multi-shot senders.
+If the caller does wish for the sender to remain valid after the call then it
+can pass an lvalue-qualified sender to the call to `execution::connect`. Such
+usages will only accept multi-shot senders.
 
-Algorithms that accept senders will typically either decay-copy an input sender and store it somewhere
-for later usage (for example as a data-member of the returned sender) or will immediately call
-`execution::connect` on the input sender, such as in `this_thread::sync_wait` or `execution::start_detached`.
+Algorithms that accept senders will typically either decay-copy an input sender
+and store it somewhere for later usage (for example as a data-member of the
+returned sender) or will immediately call `execution::connect` on the input
+sender, such as in `this_thread::sync_wait` or `execution::start_detached`.
 
-Some multi-use sender algorithms may require that an input sender be copy-constructible but will only call
-`execution::connect` on an rvalue of each copy, which still results in effectively executing the operation multiple times.
-Other multi-use sender algorithms may require that the sender is move-constructible but will invoke `execution::connect`
-on an lvalue reference to the sender.
+Some multi-use sender algorithms may require that an input sender be
+copy-constructible but will only call `execution::connect` on an rvalue of each
+copy, which still results in effectively executing the operation multiple times.
+Other multi-use sender algorithms may require that the sender is
+move-constructible but will invoke `execution::connect` on an lvalue reference
+to the sender.
 
-For a sender to be usable in both multi-use scenarios, it will generally be required to be both copy-constructible and lvalue-connectable.
+For a sender to be usable in both multi-use scenarios, it will generally be
+required to be both copy-constructible and lvalue-connectable.
 
 ## Senders are forkable ## {#design-forkable}
 
-Any non-trivial program will eventually want to fork a chain of senders into independent streams of work, regardless of whether they are single-shot or multi-shot.
-For instance, an incoming event to a middleware system may be required to trigger events on more than one downstream system.
-This requires that we provide well defined mechanisms for making sure that connecting a sender multiple times is possible and correct.
+Any non-trivial program will eventually want to fork a chain of senders into
+independent streams of work, regardless of whether they are single-shot or
+multi-shot. For instance, an incoming event to a middleware system may be
+required to trigger events on more than one downstream system. This requires
+that we provide well defined mechanisms for making sure that connecting a sender
+multiple times is possible and correct.
 
-The `split` sender adaptor facilitates connecting to a sender multiple times, regardless of whether it is single-shot or multi-shot:
+The `split` sender adaptor facilitates connecting to a sender multiple times,
+regardless of whether it is single-shot or multi-shot:
 
 
 auto some_algorithm(execution::sender auto&& input) {
@@ -1842,44 +2253,52 @@ auto some_algorithm(execution::sender auto&& input) {
 
 ## Senders support cancellation ## {#design-cancellation}
 
-Senders are often used in scenarios where the application may be concurrently executing
-multiple strategies for achieving some program goal. When one of these strategies succeeds
-(or fails) it may not make sense to continue pursuing the other strategies as their results
-are no longer useful.
+Senders are often used in scenarios where the application may be concurrently
+executing multiple strategies for achieving some program goal. When one of these
+strategies succeeds (or fails) it may not make sense to continue pursuing the
+other strategies as their results are no longer useful.
 
-For example, we may want to try to simultaneously connect to multiple network servers and use
-whichever server responds first. Once the first server responds we no longer need to continue
-trying to connect to the other servers.
+For example, we may want to try to simultaneously connect to multiple network
+servers and use whichever server responds first. Once the first server responds
+we no longer need to continue trying to connect to the other servers.
 
-Ideally, in these scenarios, we would somehow be able to request that those other strategies
-stop executing promptly so that their resources (e.g. cpu, memory, I/O bandwidth) can be
-released and used for other work.
+Ideally, in these scenarios, we would somehow be able to request that those
+other strategies stop executing promptly so that their resources (e.g. cpu,
+memory, I/O bandwidth) can be released and used for other work.
 
-While the design of senders has support for cancelling an operation before it starts
-by simply destroying the sender or the operation-state returned from `execution::connect()`
-before calling `execution::start()`, there also needs to be a standard, generic mechanism
-to ask for an already-started operation to complete early.
+While the design of senders has support for cancelling an operation before it
+starts by simply destroying the sender or the operation-state returned from
+`execution::connect()` before calling `execution::start()`, there also needs to
+be a standard, generic mechanism to ask for an already-started operation to
+complete early.
 
-The ability to be able to cancel in-flight operations is fundamental to supporting some kinds
-of generic concurrency algorithms.
+The ability to be able to cancel in-flight operations is fundamental to
+supporting some kinds of generic concurrency algorithms.
 
 For example:
-* a `when_all(ops...)` algorithm should cancel other operations as soon as one operation fails
-* a `first_successful(ops...)` algorithm should cancel the other operations as soon as one operation completes successfuly
-* a generic `timeout(src, duration)` algorithm needs to be able to cancel the `src` operation after the timeout duration has elapsed.
-* a `stop_when(src, trigger)` algorithm should cancel `src` if `trigger` completes first and cancel `trigger` if `src` completes first
-
-
-The mechanism used for communcating cancellation-requests, or stop-requests, needs to have a uniform interface
-so that generic algorithms that compose sender-based operations, such as the ones listed above, are able to
-communicate these cancellation requests to senders that they don't know anything about.
-
-The design is intended to be composable so that cancellation of higher-level operations can propagate
-those cancellation requests through intermediate layers to lower-level operations that need to actually
-respond to the cancellation requests.
+* a `when_all(ops...)` algorithm should cancel other operations as soon as one
+    operation fails
+* a `first_successful(ops...)` algorithm should cancel the other operations as
+    soon as one operation completes successfuly
+* a generic `timeout(src, duration)` algorithm needs to be able to cancel the
+    `src` operation after the timeout duration has elapsed.
+* a `stop_when(src, trigger)` algorithm should cancel `src` if `trigger`
+    completes first and cancel `trigger` if `src` completes first
+
+The mechanism used for communcating cancellation-requests, or stop-requests,
+needs to have a uniform interface so that generic algorithms that compose
+sender-based operations, such as the ones listed above, are able to communicate
+these cancellation requests to senders that they don't know anything about.
+
+The design is intended to be composable so that cancellation of higher-level
+operations can propagate those cancellation requests through intermediate layers
+to lower-level operations that need to actually respond to the cancellation
+requests.
+
+For example, we can compose the algorithms mentioned above so that child
+operations are cancelled when any one of the multiple cancellation conditions
+occurs:
 
-For example, we can compose the algorithms mentioned above so that child operations
-are cancelled when any one of the multiple cancellation conditions occurs:
 
 sender auto composed_cancellation_example(auto query) {
   return stop_when(
@@ -1894,55 +2313,78 @@ sender auto composed_cancellation_example(auto query) {
 }
 
-In this example, if we take the operation returned by `query_server_b(query)`, this operation will -receive a stop-request when any of the following happens: -* `first_successful` algorithm will send a stop-request if `query_server_a(query)` completes successfully -* `when_all` algorithm will send a stop-request if the `load_file("some_file.jpg")` operation completes with an error or stopped result. -* `timeout` algorithm will send a stop-request if the operation does not complete within 5 seconds. -* `stop_when` algorithm will send a stop-request if the user clicks on the "Cancel" button in the user-interface. -* The parent operation consuming the `composed_cancellation_example()` sends a stop-request - - -Note that within this code there is no explicit mention of cancellation, stop-tokens, callbacks, etc. -yet the example fully supports and responds to the various cancellation sources. - -The intent of the design is that the common usage of cancellation in sender/receiver-based code is -primarily through use of concurrency algorithms that manage the detailed plumbing of cancellation -for you. Much like algorithms that compose senders relieve the user from having to write their own -receiver types, algorithms that introduce concurrency and provide higher-level cancellation semantics -relieve the user from having to deal with low-level details of cancellation. +In this example, if we take the operation returned by `query_server_b(query)`, +this operation will receive a stop-request when any of the following happens: + +* `first_successful` algorithm will send a stop-request if + `query_server_a(query)` completes successfully +* `when_all` algorithm will send a stop-request if the + `load_file("some_file.jpg")` operation completes with an error or stopped + result. +* `timeout` algorithm will send a stop-request if the operation does not + complete within 5 seconds. +* `stop_when` algorithm will send a stop-request if the user clicks on the + "Cancel" button in the user-interface. +* The parent operation consuming the `composed_cancellation_example()` sends a + stop-request + +Note that within this code there is no explicit mention of cancellation, +stop-tokens, callbacks, etc. yet the example fully supports and responds to the +various cancellation sources. + +The intent of the design is that the common usage of cancellation in +sender/receiver-based code is primarily through use of concurrency algorithms +that manage the detailed plumbing of cancellation for you. Much like algorithms +that compose senders relieve the user from having to write their own receiver +types, algorithms that introduce concurrency and provide higher-level +cancellation semantics relieve the user from having to deal with low-level +details of cancellation. ### Cancellation design summary ### {#design-cancellation-summary} -The design of cancellation described in this paper is built on top of and extends the `std::stop_token`-based -cancellation facilities added in C++20, first proposed in [[P2175R0]]. - -At a high-level, the facilities proposed by this paper for supporting cancellation include: -* Add `std::stoppable_token` and `std::stoppable_token_for` concepts that generalise the interface of `std::stop_token` type to allow other types with different implementation strategies. -* Add `std::unstoppable_token` concept for detecting whether a `stoppable_token` can never receive a stop-request. -* Add `std::in_place_stop_token`, `std::in_place_stop_source` and `std::in_place_stop_callback` types that provide a more efficient implementation of a stop-token for use in structured concurrency situations. -* Add `std::never_stop_token` for use in places where you never want to issue a stop-request -* Add `std::execution::get_stop_token()` CPO for querying the stop-token to use for an operation from its receiver's execution environment. -* Add `std::execution::stop_token_of_t` for querying the type of a stop-token returned from `get_stop_token()` - -In addition, there are requirements added to some of the algorithms to specify what their cancellation -behaviour is and what the requirements of customisations of those algorithms are with respect to -cancellation. - -The key component that enables generic cancellation within sender-based operations is the `execution::get_stop_token()` CPO. -This CPO takes a single parameter, which is the execution environment of the receiver passed to `execution::connect`, and returns a `std::stoppable_token` -that the operation can use to check for stop-requests for that operation. +The design of cancellation described in this paper is built on top of and +extends the `std::stop_token`-based cancellation facilities added in C++20, +first proposed in [[P2175R0]]. + +At a high-level, the facilities proposed by this paper for supporting +cancellation include: + +* Add `std::stoppable_token` and `std::stoppable_token_for` concepts that + generalise the interface of `std::stop_token` type to allow other types with + different implementation strategies. +* Add `std::unstoppable_token` concept for detecting whether a `stoppable_token` + can never receive a stop-request. +* Add `std::in_place_stop_token`, `std::in_place_stop_source` and + `std::in_place_stop_callback` types that provide a more efficient + implementation of a stop-token for use in structured concurrency situations. +* Add `std::never_stop_token` for use in places where you never want to issue a + stop-request. +* Add `std::execution::get_stop_token()` CPO for querying the stop-token to use + for an operation from its receiver's execution environment. +* Add `std::execution::stop_token_of_t` for querying the type of a stop-token + returned from `get_stop_token()`. + +In addition, there are requirements added to some of the algorithms to specify +what their cancellation behaviour is and what the requirements of customisations +of those algorithms are with respect to cancellation. + +The key component that enables generic cancellation within sender-based +operations is the `execution::get_stop_token()` CPO. This CPO takes a single +parameter, which is the execution environment of the receiver passed to +`execution::connect`, and returns a `std::stoppable_token` that the operation +can use to check for stop-requests for that operation. As the caller of `execution::connect` typically has control over the receiver -type it passes, it is able to customise the `std::execution::get_env()` CPO for that -receiver to return an execution environment that hooks the +type it passes, it is able to customise the `std::execution::get_env()` CPO for +that receiver to return an execution environment that hooks the `execution::get_stop_token()` CPO to return a stop-token that the receiver has control over and that it can use to communicate a stop-request to the operation once it has started. ### Support for cancellation is optional ### {#design-cancellation-optional} -Support for cancellation is optional, both on part of the author of the receiver and on part of the author of the sender. +Support for cancellation is optional, both on part of the author of the receiver +and on part of the author of the sender. If the receiver's execution environment does not customise the `execution::get_stop_token()` CPO then invoking the CPO on that receiver's @@ -1950,58 +2392,78 @@ environment will invoke the default implementation which returns `std::never_stop_token`. This is a special `stoppable_token` type that is statically known to always return `false` from the `stop_possible()` method. -Sender code that tries to use this stop-token will in general result in code that handles stop-requests being -compiled out and having little to no run-time overhead. +Sender code that tries to use this stop-token will in general result in code +that handles stop-requests being compiled out and having little to no run-time +overhead. -If the sender doesn't call `execution::get_stop_token()`, for example because the operation does not support -cancellation, then it will simply not respond to stop-requests from the caller. +If the sender doesn't call `execution::get_stop_token()`, for example because +the operation does not support cancellation, then it will simply not respond to +stop-requests from the caller. -Note that stop-requests are generally racy in nature as there is often a race betwen an operation completing -naturally and the stop-request being made. If the operation has already completed or past the point at which -it can be cancelled when the stop-request is sent then the stop-request may just be ignored. An application -will typically need to be able to cope with senders that might ignore a stop-request anyway. +Note that stop-requests are generally racy in nature as there is often a race +betwen an operation completing naturally and the stop-request being made. If the +operation has already completed or past the point at which it can be cancelled +when the stop-request is sent then the stop-request may just be ignored. An +application will typically need to be able to cope with senders that might +ignore a stop-request anyway. ### Cancellation is inherently racy ### {#design-cancellation-racy} -Usually, an operation will attach a stop-callback at some point inside the call to `execution::start()` so that -a subsequent stop-request will interrupt the logic. - -A stop-request can be issued concurrently from another thread. This means the implementation of `execution::start()` -needs to be careful to ensure that, once a stop-callback has been registered, that there are no data-races between -a potentially concurrently-executing stop-callback and the rest of the `execution::start()` implementation. - -An implementation of `execution::start()` that supports cancellation will generally need to perform (at least) -two separate steps: launch the operation, subscribe a stop-callback to the receiver's stop-token. Care needs -to be taken depending on the order in which these two steps are performed. - -If the stop-callback is subscribed first and then the operation is launched, care needs to be taken to ensure -that a stop-request that invokes the stop-callback on another thread after the stop-callback is registered -but before the operation finishes launching does not either result in a missed cancellation request or a -data-race. e.g. by performing an atomic write after the launch has finished executing - -If the operation is launched first and then the stop-callback is subscribed, care needs to be taken to ensure -that if the launched operation completes concurrently on another thread that it does not destroy the operation-state -until after the stop-callback has been registered. e.g. by having the `execution::start` implementation write to -an atomic variable once it has finished registering the stop-callback and having the concurrent completion handler -check that variable and either call the completion-signalling operation or store the result and defer calling the -receiver's completion-signalling operation to the `execution::start()` call (which is still executing). - -For an example of an implementation strategy for solving these data-races see [[#example-async-windows-socket-recv]]. +Usually, an operation will attach a stop-callback at some point inside the call +to `execution::start()` so that a subsequent stop-request will interrupt the +logic. + +A stop-request can be issued concurrently from another thread. This means the +implementation of `execution::start()` needs to be careful to ensure that, once +a stop-callback has been registered, that there are no data-races between a +potentially concurrently-executing stop-callback and the rest of the +`execution::start()` implementation. + +An implementation of `execution::start()` that supports cancellation will +generally need to perform (at least) two separate steps: launch the operation, +subscribe a stop-callback to the receiver's stop-token. Care needs to be taken +depending on the order in which these two steps are performed. + +If the stop-callback is subscribed first and then the operation is launched, +care needs to be taken to ensure that a stop-request that invokes the +stop-callback on another thread after the stop-callback is registered but before +the operation finishes launching does not either result in a missed cancellation +request or a data-race. e.g. by performing an atomic write after the launch has +finished executing + +If the operation is launched first and then the stop-callback is subscribed, +care needs to be taken to ensure that if the launched operation completes +concurrently on another thread that it does not destroy the operation-state +until after the stop-callback has been registered. e.g. by having the +`execution::start` implementation write to an atomic variable once it has +finished registering the stop-callback and having the concurrent completion +handler check that variable and either call the completion-signalling operation +or store the result and defer calling the receiver's completion-signalling +operation to the `execution::start()` call (which is still executing). + +For an example of an implementation strategy for solving these data-races see +[[#example-async-windows-socket-recv]]. ### Cancellation design status ### {#design-cancellation-status} This paper currently includes the design for cancellation as proposed in [[P2175R0]] - "Composable cancellation for sender-based async operations". -P2175R0 contains more details on the background motivation and prior-art and design rationale of this design. +P2175R0 contains more details on the background motivation and prior-art and +design rationale of this design. -It is important to note, however, that initial review of this design in the SG1 concurrency subgroup raised some concerns -related to runtime overhead of the design in single-threaded scenarios and these concerns are still being investigated. +It is important to note, however, that initial review of this design in the SG1 +concurrency subgroup raised some concerns related to runtime overhead of the +design in single-threaded scenarios and these concerns are still being +investigated. -The design of P2175R0 has been included in this paper for now, despite its potential to change, as we believe that -support for cancellation is a fundamental requirement for an async model and is required in some form to be able to -talk about the semantics of some of the algorithms proposed in this paper. +The design of P2175R0 has been included in this paper for now, despite its +potential to change, as we believe that support for cancellation is a +fundamental requirement for an async model and is required in some form to be +able to talk about the semantics of some of the algorithms proposed in this +paper. -This paper will be updated in the future with any changes that arise from the investigations into P2175R0. +This paper will be updated in the future with any changes that arise from the +investigations into P2175R0. ## Sender factories and adaptors are lazy ## {#design-lazy-algorithms} @@ -2010,24 +2472,26 @@ executing their logic eagerly; i.e., before the returned sender has been connected to a receiver and started. These algorithms were removed because eager execution has a number of negative semantic and performance implications. -We have originally included this functionality in the paper because of a long-standing -belief that eager execution is a mandatory feature to be included in the standard Executors -facility for that facility to be acceptable for accelerator vendors. A particular concern -was that we must be able to write generic algorithms that can run either eagerly or lazily, -depending on the kind of an input sender or scheduler that have been passed into them as -arguments. We considered this a requirement, because the _latency_ of launching work on an +We have originally included this functionality in the paper because of a +long-standing belief that eager execution is a mandatory feature to be included +in the standard Executors facility for that facility to be acceptable for +accelerator vendors. A particular concern was that we must be able to write +generic algorithms that can run either eagerly or lazily, depending on the kind +of an input sender or scheduler that have been passed into them as arguments. We +considered this a requirement, because the _latency_ of launching work on an accelerator can sometimes be considerable. -However, in the process of working on this paper and implementations of the features -proposed within, our set of requirements has shifted, as we understood the different -implementation strategies that are available for the feature set of this paper better, -and, after weighting the earlier concerns against the points presented below, we -have arrived at the conclusion that a purely lazy model is enough for most algorithms, -and users who intend to launch work earlier may use an algorithm such as `ensure_started` -to achieve that goal. We have also come to deeply appreciate the fact that a purely -lazy model allows both the implementation and the compiler to have a much better -understanding of what the complete graph of tasks looks like, allowing them to better -optimize the code - also when targetting accelerators. +However, in the process of working on this paper and implementations of the +features proposed within, our set of requirements has shifted, as we understood +the different implementation strategies that are available for the feature set +of this paper better, and, after weighting the earlier concerns against the +points presented below, we have arrived at the conclusion that a purely lazy +model is enough for most algorithms, and users who intend to launch work earlier +may use an algorithm such as `ensure_started` to achieve that goal. We have also +come to deeply appreciate the fact that a purely lazy model allows both the +implementation and the compiler to have a much better understanding of what the +complete graph of tasks looks like, allowing them to better optimize the code - +also when targetting accelerators. ### Eager execution leads to detached work or worse ### {#design-lazy-algorithms-detached} @@ -2173,23 +2637,36 @@ child operations, which may complete before a receiver is ever attached. ## Schedulers advertise their forward progress guarantees ## {#design-fpg} -To decide whether a scheduler (and its associated execution resource) is sufficient for a specific task, it may be necessary to know what kind of forward progress guarantees it provides for the execution agents it creates. The C++ Standard defines the following -forward progress guarantees: +To decide whether a scheduler (and its associated execution resource) is +sufficient for a specific task, it may be necessary to know what kind of forward +progress guarantees it provides for the execution agents it creates. The C++ +Standard defines the following forward progress guarantees: -* concurrent, which requires that a thread makes progress eventually; -* parallel, which requires that a thread makes progress once it executes a step; and +* concurrent, which requires that a thread makes progress + eventually; +* parallel, which requires that a thread makes progress once it executes + a step; and * weakly parallel, which does not require that the thread makes progress. -This paper introduces a scheduler query function, `get_forward_progress_guarantee`, which returns one of the enumerators of a new `enum` type, `forward_progress_guarantee`. Each enumerator of `forward_progress_guarantee` corresponds to one of the aforementioned +This paper introduces a scheduler query function, +`get_forward_progress_guarantee`, which returns one of the enumerators of a new +`enum` type, `forward_progress_guarantee`. Each enumerator of +`forward_progress_guarantee` corresponds to one of the aforementioned guarantees. ## Most sender adaptors are pipeable ## {#design-pipeable} -To facilitate an intuitive syntax for composition, most sender adaptors are pipeable; they can be composed (piped) together with `operator|`. -This mechanism is similar to the `operator|` composition that C++ range adaptors support and draws inspiration from piping in *nix shells. -Pipeable sender adaptors take a sender as their first parameter and have no other sender parameters. +To facilitate an intuitive syntax for composition, most sender adaptors are pipeable; they can be composed (piped) +together with `operator|`. This mechanism is similar to the `operator|` +composition that C++ range adaptors support and draws inspiration from piping in +*nix shells. +Pipeable sender adaptors take a sender as their first parameter and have no +other sender parameters. -`a | b` will pass the sender `a` as the first argument to the pipeable sender adaptor `b`. Pipeable sender adaptors support partial application of the parameters after the first. For example, all of the following are equivalent: +`a | b` will pass the sender `a` as the first argument to the pipeable sender +adaptor `b`. Pipeable sender adaptors support partial application of the +parameters after the first. For example, all of the following are equivalent:
 execution::bulk(snd, N, [] (std::size_t i, auto d) {});
@@ -2197,9 +2674,12 @@ execution::bulk(N, [] (std::size_t i, auto d) {})(snd);
 snd | execution::bulk(N, [] (std::size_t i, auto d) {});
 
-Piping enables you to compose together senders with a linear syntax. -Without it, you'd have to use either nested function call syntax, which would cause a syntactic inversion of the direction of control flow, or you'd have to introduce a temporary variable for each stage of the pipeline. -Consider the following example where we want to execute first on a CPU thread pool, then on a CUDA GPU, then back on the CPU thread pool: +Piping enables you to compose together senders with a linear syntax. Without it, +you'd have to use either nested function call syntax, which would cause a +syntactic inversion of the direction of control flow, or you'd have to introduce +a temporary variable for each stage of the pipeline. Consider the following +example where we want to execute first on a CPU thread pool, then on a CUDA GPU, +then back on the CPU thread pool: @@ -2248,20 +2728,35 @@ auto [result] = this_thread::sync_wait(snd).value();
-Certain sender adaptors are not pipeable, because using the pipeline syntax can result in confusion of the semantics of the adaptors involved. Specifically, the following sender adaptors are not pipeable. +Certain sender adaptors are not pipeable, because using the pipeline syntax can +result in confusion of the semantics of the adaptors involved. Specifically, the +following sender adaptors are not pipeable. -* `execution::when_all` and `execution::when_all_with_variant`: Since this sender adaptor takes a variadic pack of senders, a partially applied form would be ambiguous with a non partially applied form with an arity of one less. -* `execution::on`: This sender adaptor changes how the sender passed to it is executed, not what happens to its result, but allowing it in a pipeline makes it read as if it performed a function more similar to `transfer`. +* `execution::when_all` and `execution::when_all_with_variant`: Since this + sender adaptor takes a variadic pack of senders, a partially applied form + would be ambiguous with a non partially applied form with an arity of one + less. +* `execution::on`: This sender adaptor changes how the sender passed to it is + executed, not what happens to its result, but allowing it in a pipeline makes + it read as if it performed a function more similar to `transfer`. Sender consumers could be made pipeable, but we have chosen to not do so. -However, since these are terminal nodes in a pipeline and nothing can be piped after them, we believe a pipe syntax may be confusing as well as unnecessary, as consumers cannot be chained. -We believe sender consumers read better with function call syntax. +However, since these are terminal nodes in a pipeline and nothing can be piped +after them, we believe a pipe syntax may be confusing as well as unnecessary, as +consumers cannot be chained. We believe sender consumers read better with +function call syntax. ## A range of senders represents an async sequence of data ## {#design-range-of-senders} -Senders represent a single unit of asynchronous work. In many cases though, what is being modelled is a sequence of data arriving asynchronously, and you want computation to happen on demand, when each element arrives. This requires nothing more than what is in this paper and the range support in C++20. A range of senders would allow you to model such input as keystrikes, mouse movements, sensor readings, or network requests. +Senders represent a single unit of asynchronous work. In many cases though, what +is being modelled is a sequence of data arriving asynchronously, and you want +computation to happen on demand, when each element arrives. This requires +nothing more than what is in this paper and the range support in C++20. A range +of senders would allow you to model such input as keystrikes, mouse movements, +sensor readings, or network requests. -Given some expression R that is a range of senders, consider the following in a coroutine that returns an async generator type: +Given some expression R that is a range of senders, consider +the following in a coroutine that returns an async generator type:
     for (auto snd : R) {
@@ -2272,17 +2767,35 @@ Given some expression R that is a range of senders, consider
     }
     
-This transforms each element of the asynchronous sequence R with the function `fn` on demand, as the data arrives. The result is a new asynchronous sequence of the transformed values. +This transforms each element of the asynchronous sequence R +with the function `fn` on demand, as the data arrives. The result is a new +asynchronous sequence of the transformed values. -Now imagine that R is the simple expression `views::iota(0) | views::transform(execution::just)`. This creates a lazy range of senders, each of which completes immediately with monotonically increasing integers. The above code churns through the range, generating a new infine asynchronous range of values [`fn(0)`, `fn(1)`, `fn(2)`, ...]. +Now imagine that R is the simple expression `views::iota(0) +| views::transform(execution::just)`. This creates a lazy range of senders, each +of which completes immediately with monotonically increasing integers. The above +code churns through the range, generating a new infine asynchronous range of +values [`fn(0)`, `fn(1)`, `fn(2)`, ...]. -Far more interesting would be if R were a range of senders representing, say, user actions in a UI. The above code gives a simple way to respond to user actions on demand. +Far more interesting would be if R were a range of senders +representing, say, user actions in a UI. The above code gives a simple way to +respond to user actions on demand. ## Senders can represent partial success ## {#design-partial-success} -Receivers have three ways they can complete: with success, failure, or cancellation. This begs the question of how they can be used to represent async operations that *partially* succeed. For example, consider an API that reads from a socket. The connection could drop after the API has filled in some of the buffer. In cases like that, it makes sense to want to report both that the connection dropped and that some data has been successfully read. +Receivers have three ways they can complete: with success, failure, or +cancellation. This begs the question of how they can be used to represent async +operations that *partially* succeed. For example, consider an API that reads +from a socket. The connection could drop after the API has filled in some of the +buffer. In cases like that, it makes sense to want to report both that the +connection dropped and that some data has been successfully read. -Often in the case of partial success, the error condition is not fatal nor does it mean the API has failed to satisfy its post-conditions. It is merely an extra piece of information about the nature of the completion. In those cases, "partial success" is another way of saying "success". As a result, it is sensible to pass both the error code and the result (if any) through the value channel, as shown below: +Often in the case of partial success, the error condition is not fatal nor does +it mean the API has failed to satisfy its post-conditions. It is merely an extra +piece of information about the nature of the completion. In those cases, +"partial success" is another way of saying "success". As a result, it is +sensible to pass both the error code and the result (if any) through the value +channel, as shown below:
     // Capture a buffer for read_socket_async to fill in
@@ -2302,9 +2815,21 @@ Often in the case of partial success, the error condition is not fatal nor does
         })
     
-In other cases, the partial success is more of a partial *failure*. That happens when the error condition indicates that in some way the function failed to satisfy its post-conditions. In those cases, sending the error through the value channel loses valuable contextual information. It's possible that bundling the error and the incomplete results into an object and passing it through the error channel makes more sense. In that way, generic algorithms will not miss the fact that a post-condition has not been met and react inappropriately. - -Another possibility is for an async API to return a *range* of senders: if the API completes with full success, full error, or cancellation, the returned range contains just one sender with the result. Otherwise, if the API partially fails (doesn't satisfy its post-conditions, but some incomplete result is available), the returned range would have *two* senders: the first containing the partial result, and the second containing the error. Such an API might be used in a coroutine as follows: +In other cases, the partial success is more of a partial *failure*. That happens +when the error condition indicates that in some way the function failed to +satisfy its post-conditions. In those cases, sending the error through the value +channel loses valuable contextual information. It's possible that bundling the +error and the incomplete results into an object and passing it through the error +channel makes more sense. In that way, generic algorithms will not miss the fact +that a post-condition has not been met and react inappropriately. + +Another possibility is for an async API to return a *range* of senders: if the +API completes with full success, full error, or cancellation, the returned range +contains just one sender with the result. Otherwise, if the API partially fails +(doesn't satisfy its post-conditions, but some incomplete result is available), +the returned range would have *two* senders: the first containing the partial +result, and the second containing the error. Such an API might be used in a +coroutine as follows:
     // Declare a buffer for read_socket_async to fill in
@@ -2326,11 +2851,18 @@ Another possibility is for an async API to return a *range* of senders: if the A
     }
     
-Finally, it's possible to combine these two approaches when the API can both partially succeed (meeting its post-conditions) and partially fail (not meeting its post-conditions). +Finally, it's possible to combine these two approaches when the API can both +partially succeed (meeting its post-conditions) and partially fail (not meeting +its post-conditions). ## All awaitables are senders ## {#design-awaitables-are-senders} -Since C++20 added coroutines to the standard, we expect that coroutines and awaitables will be how a great many will choose to express their asynchronous code. However, in this paper, we are proposing to add a suite of asynchronous algorithms that accept senders, not awaitables. One might wonder whether and how these algorithms will be accessible to those who choose coroutines instead of senders. +Since C++20 added coroutines to the standard, we expect that coroutines and +awaitables will be how a great many will choose to express their asynchronous +code. However, in this paper, we are proposing to add a suite of asynchronous +algorithms that accept senders, not awaitables. One might wonder whether and how +these algorithms will be accessible to those who choose coroutines instead of +senders. In truth there will be no problem because all generally awaitable types automatically model the `sender` concept. The adaptation is transparent and @@ -2353,13 +2885,22 @@ int main() { } ``` -Since awaitables are senders, writing a sender-based asynchronous algorithm is trivial if you have a coroutine task type: implement the algorithm as a coroutine. If you are not bothered by the possibility of allocations and indirections as a result of using coroutines, then there is no need to ever write a sender, a receiver, or an operation state. +Since awaitables are senders, writing a sender-based asynchronous algorithm is +trivial if you have a coroutine task type: implement the algorithm as a +coroutine. If you are not bothered by the possibility of allocations and +indirections as a result of using coroutines, then there is no need to ever +write a sender, a receiver, or an operation state. ## Many senders can be trivially made awaitable ## {#design-senders-are-awaitable} -If you choose to implement your sender-based algorithms as coroutines, you'll run into the issue of how to retrieve results from a passed-in sender. This is not a problem. If the coroutine type opts in to sender support -- trivial with the `execution::with_awaitable_senders` utility -- then a large class of senders are transparently awaitable from within the coroutine. +If you choose to implement your sender-based algorithms as coroutines, you'll +run into the issue of how to retrieve results from a passed-in sender. This is +not a problem. If the coroutine type opts in to sender support -- trivial with +the `execution::with_awaitable_senders` utility -- then a large class of senders +are transparently awaitable from within the coroutine. -For example, consider the following trivial implementation of the sender-based `retry` algorithm: +For example, consider the following trivial implementation of the sender-based +`retry` algorithm:
 template<class S>
@@ -2374,15 +2915,41 @@ task<single-sender-value-type<S>> retry(S s) {
 }
 
-Only *some* senders can be made awaitable directly because of the fact that callbacks are more expressive than coroutines. An awaitable expression has a single type: the result value of the async operation. In contrast, a callback can accept multiple arguments as the result of an operation. What's more, the callback can have overloaded function call signatures that take different sets of arguments. There is no way to automatically map such senders into awaitables. The `with_awaitable_senders` utility recognizes as awaitables those senders that send a single value of a single type. To await another kind of sender, a user would have to first map its value channel into a single value of a single type -- say, with the `into_variant` sender algorithm -- before `co_await`-ing that sender. +Only *some* senders can be made awaitable directly because of the fact that +callbacks are more expressive than coroutines. An awaitable expression has a +single type: the result value of the async operation. In contrast, a callback +can accept multiple arguments as the result of an operation. What's more, the +callback can have overloaded function call signatures that take different sets +of arguments. There is no way to automatically map such senders into awaitables. +The `with_awaitable_senders` utility recognizes as awaitables those senders that +send a single value of a single type. To await another kind of sender, a user +would have to first map its value channel into a single value of a single type +-- say, with the `into_variant` sender algorithm -- before `co_await`-ing that +sender. ## Cancellation of a sender can unwind a stack of coroutines ## {#design-native-coro-unwind} -When looking at the sender-based `retry` algorithm in the previous section, we can see that the value and error cases are correctly handled. But what about cancellation? What happens to a coroutine that is suspended awaiting a sender that completes by calling `execution::set_stopped`? - -When your task type's promise inherits from `with_awaitable_senders`, what happens is this: the coroutine behaves as if an *uncatchable exception* had been thrown from the `co_await` expression. (It is not really an exception, but it's helpful to think of it that way.) Provided that the promise types of the calling coroutines also inherit from `with_awaitable_senders`, or more generally implement a member function called `unhandled_stopped`, the exception unwinds the chain of coroutines as if an exception were thrown except that it bypasses `catch(...)` clauses. - -In order to "catch" this uncatchable stopped exception, one of the calling coroutines in the stack would have to await a sender that maps the stopped channel into either a value or an error. That is achievable with the `execution::let_stopped`, `execution::upon_stopped`, `execution::stopped_as_optional`, or `execution::stopped_as_error` sender adaptors. For instance, we can use `execution::stopped_as_optional` to "catch" the stopped signal and map it into an empty optional as shown below: +When looking at the sender-based `retry` algorithm in the previous section, we +can see that the value and error cases are correctly handled. But what about +cancellation? What happens to a coroutine that is suspended awaiting a sender +that completes by calling `execution::set_stopped`? + +When your task type's promise inherits from `with_awaitable_senders`, what +happens is this: the coroutine behaves as if an *uncatchable exception* had been +thrown from the `co_await` expression. (It is not really an exception, but it's +helpful to think of it that way.) Provided that the promise types of the calling +coroutines also inherit from `with_awaitable_senders`, or more generally +implement a member function called `unhandled_stopped`, the exception unwinds +the chain of coroutines as if an exception were thrown except that it bypasses +`catch(...)` clauses. + +In order to "catch" this uncatchable stopped exception, one of the calling +coroutines in the stack would have to await a sender that maps the stopped +channel into either a value or an error. That is achievable with the +`execution::let_stopped`, `execution::upon_stopped`, +`execution::stopped_as_optional`, or `execution::stopped_as_error` sender +adaptors. For instance, we can use `execution::stopped_as_optional` to "catch" +the stopped signal and map it into an empty optional as shown below: ```c++ if (auto opt = co_await execution::stopped_as_optional(some_sender)) { @@ -2392,18 +2959,37 @@ if (auto opt = co_await execution::stopped_as_optional(some_sender)) { } ``` -As described in the section "All awaitables are senders", the sender customization points recognize awaitables and adapt them transparently to model the sender concept. When `connect`-ing an awaitable and a receiver, the adaptation layer awaits the awaitable within a coroutine that implements `unhandled_stopped` in its promise type. The effect of this is that an "uncatchable" stopped exception propagates seamlessly out of awaitables, causing `execution::set_stopped` to be called on the receiver. - -Obviously, `unhandled_stopped` is a library extension of the coroutine promise interface. Many promise types will not implement `unhandled_stopped`. When an uncatchable stopped exception tries to propagate through such a coroutine, it is treated as an unhandled exception and `terminate` is called. The solution, as described above, is to use a sender adaptor to handle the stopped exception before awaiting it. It goes without saying that any future Standard Library coroutine types ought to implement `unhandled_stopped`. The author of [[P1056R1]], which proposes a standard coroutine task type, is in agreement. +As described in the section "All +awaitables are senders", the sender customization points recognize +awaitables and adapt them transparently to model the sender concept. When +`connect`-ing an awaitable and a receiver, the adaptation layer awaits the +awaitable within a coroutine that implements `unhandled_stopped` in its promise +type. The effect of this is that an "uncatchable" stopped exception propagates +seamlessly out of awaitables, causing `execution::set_stopped` to be called on +the receiver. + +Obviously, `unhandled_stopped` is a library extension of the coroutine promise +interface. Many promise types will not implement `unhandled_stopped`. When an +uncatchable stopped exception tries to propagate through such a coroutine, it is +treated as an unhandled exception and `terminate` is called. The solution, as +described above, is to use a sender adaptor to handle the stopped exception +before awaiting it. It goes without saying that any future Standard Library +coroutine types ought to implement `unhandled_stopped`. The author of +[[P1056R1]], which proposes a standard coroutine task type, is in agreement. ## Composition with parallel algorithms ## {#design-parallel-algorithms} -The C++ Standard Library provides a large number of algorithms that offer the potential for non-sequential execution via the use of execution policies. The set of algorithms with execution policy overloads are often referred to as "parallel algorithms", although -additional policies are available. +The C++ Standard Library provides a large number of algorithms that offer the +potential for non-sequential execution via the use of execution policies. The +set of algorithms with execution policy overloads are often referred to as +"parallel algorithms", although additional policies are available. -Existing policies, such as `execution::par`, give the implementation permission to execute the algorithm in parallel. However, the choice of execution resources used to perform the work is left to the implementation. +Existing policies, such as `execution::par`, give the implementation permission +to execute the algorithm in parallel. However, the choice of execution resources +used to perform the work is left to the implementation. -We will propose a customization point for combining schedulers with policies in order to provide control over where work will execute. +We will propose a customization point for combining schedulers with policies in +order to provide control over where work will execute.
 template<class ExecutionPolicy>
@@ -2413,17 +2999,27 @@ template<class ExecutionPolicy>
 );
 
-This function would return an object of an unspecified type which can be used in place of an execution policy as the first argument to one of the parallel algorithms. The overload selected by that object should execute its computation as requested by -`policy` while using `scheduler` to create any work to be run. The expression may be ill-formed if `scheduler` is not able to support the given policy. +This function would return an object of an unspecified type which can be used in +place of an execution policy as the first argument to one of the parallel +algorithms. The overload selected by that object should execute its computation +as requested by `policy` while using `scheduler` to create any work to be run. +The expression may be ill-formed if `scheduler` is not able to support the given +policy. -The existing parallel algorithms are synchronous; all of the effects performed by the computation are complete before the algorithm returns to its caller. This remains unchanged with the `executing_on` customization point. +The existing parallel algorithms are synchronous; all of the effects performed +by the computation are complete before the algorithm returns to its caller. This +remains unchanged with the `executing_on` customization point. -In the future, we expect additional papers will propose asynchronous forms of the parallel algorithms which (1) return senders rather than values or `void` and (2) where a customization point pairing a sender with an execution policy would similarly be used to -obtain an object of unspecified type to be provided as the first argument to the algorithm. +In the future, we expect additional papers will propose asynchronous forms of +the parallel algorithms which (1) return senders rather than values or `void` +and (2) where a customization point pairing a sender with an execution policy +would similarly be used to obtain an object of unspecified type to be provided +as the first argument to the algorithm. ## User-facing sender factories ## {#design-sender-factories} -A [=sender factory=] is an algorithm that takes no senders as parameters and returns a sender. +A [=sender factory=] is an algorithm that takes no senders as parameters and +returns a sender. ### `execution::schedule` ### {#design-sender-factory-schedule} @@ -2433,7 +3029,8 @@ execution::sender auto schedule( );
-Returns a sender describing the start of a task graph on the provided scheduler. See [[#design-schedulers]]. +Returns a sender describing the start of a task graph on the provided scheduler. +See [[#design-schedulers]].
 execution::scheduler auto sch1 = get_system_thread_pool().scheduler();
@@ -2450,7 +3047,12 @@ execution::sender auto just(
 );
 
-Returns a sender with no [=completion scheduler|completion schedulers=], which [=send|sends=] the provided values. The input values are decay-copied into the returned sender. When the returned sender is connected to a receiver, the values are moved into the operation state if the sender is an rvalue; otherwise, they are copied. Then xvalues referencing the values in the operation state are passed to the receiver's `set_value`. +Returns a sender with no [=completion scheduler|completion schedulers=], which +[=send|sends=] the provided values. The input values are decay-copied into the +returned sender. When the returned sender is connected to a receiver, the values +are moved into the operation state if the sender is an rvalue; otherwise, they +are copied. Then xvalues referencing the values in the operation state are +passed to the receiver's `set_value`. ```c++ execution::sender auto snd1 = execution::just(3.14); @@ -2489,7 +3091,12 @@ execution::sender auto just_error( );
-Returns a sender with no [=completion scheduler|completion schedulers=], which completes with the specified error. If the provided error is an lvalue reference, a copy is made inside the returned sender and a non-const lvalue reference to the copy is sent to the receiver's `set_error`. If the provided value is an rvalue reference, it is moved into the returned sender and an rvalue reference to it is sent to the receiver's `set_error`. +Returns a sender with no [=completion scheduler|completion schedulers=], which +completes with the specified error. If the provided error is an lvalue +reference, a copy is made inside the returned sender and a non-const lvalue +reference to the copy is sent to the receiver's `set_error`. If the provided +value is an rvalue reference, it is moved into the returned sender and an rvalue +reference to it is sent to the receiver's `set_error`. ### `execution::just_stopped` ### {#design-sender-factory-just_stopped} @@ -2497,7 +3104,8 @@ Returns a sender with no [=completion scheduler|completion schedulers=], which c execution::sender auto just_stopped();
-Returns a sender with no [=completion scheduler|completion schedulers=], which completes immediately by calling the receiver's `set_stopped`. +Returns a sender with no [=completion scheduler|completion schedulers=], which +completes immediately by calling the receiver's `set_stopped`. ### `execution::read` ### {#design-sender-factory-read} @@ -2518,9 +3126,16 @@ execution::sender auto get_stop_token() { }
-Returns a sender that reaches into a receiver's environment and pulls out the current value associated with the customization point denoted by `Tag`. It then sends the value read back to the receiver through the value channel. For instance, `get_scheduler()` (with no arguments) is a sender that asks the receiver for the currently suggested `scheduler` and passes it to the receiver's `set_value` completion-signal. +Returns a sender that reaches into a receiver's environment and pulls out the +current value associated with the customization point denoted by `Tag`. It then +sends the value read back to the receiver through the value channel. For +instance, `get_scheduler()` (with no arguments) is a sender that asks the +receiver for the currently suggested `scheduler` and passes it to the receiver's +`set_value` completion-signal. -This can be useful when scheduling nested dependent work. The following sender pulls the current schduler into the value channel and then schedules more work onto it. +This can be useful when scheduling nested dependent work. The following sender +pulls the current schduler into the value channel and then schedules more work +onto it.
     execution::sender auto task =
@@ -2532,16 +3147,27 @@ This can be useful when scheduling nested dependent work. The following sender p
     this_thread::sync_wait( std::move(task) ); // wait for it to finish
     
-This code uses the fact that `sync_wait` associates a scheduler with the receiver that it connects with `task`. `get_scheduler()` reads that scheduler out of the receiver, and passes it to `let_value`'s receiver's `set_value` function, which in turn passes it to the lambda. That lambda returns a new sender that uses the scheduler to schedule some nested work onto `sync_wait`'s scheduler. +This code uses the fact that `sync_wait` associates a scheduler with the +receiver that it connects with `task`. `get_scheduler()` reads that scheduler +out of the receiver, and passes it to `let_value`'s receiver's `set_value` +function, which in turn passes it to the lambda. That lambda returns a new +sender that uses the scheduler to schedule some nested work onto `sync_wait`'s +scheduler. ## User-facing sender adaptors ## {#design-sender-adaptors} -A [=sender adaptor=] is an algorithm that takes one or more senders, which it may `execution::connect`, as parameters, and returns a sender, whose completion is related to the sender arguments it has received. +A [=sender adaptor=] is an algorithm that takes one or more senders, which it +may `execution::connect`, as parameters, and returns a sender, whose completion +is related to the sender arguments it has received. -Sender adaptors are lazy, that is, they are never allowed to submit any work for execution prior to the returned sender being [=started=] later on, and are also guaranteed to not start any input senders passed into them. Sender consumers -such as [[#design-sender-consumer-start_detached]] and [[#design-sender-consumer-sync_wait]] start senders. +Sender adaptors are lazy, that is, they are never allowed to submit any +work for execution prior to the returned sender being [=started=] later on, and +are also guaranteed to not start any input senders passed into them. Sender +consumers such as [[#design-sender-consumer-start_detached]] and +[[#design-sender-consumer-sync_wait]] start senders. -For more implementer-centric description of starting senders, see [[#design-laziness]]. +For more implementer-centric description of starting senders, see +[[#design-laziness]]. ### `execution::transfer` ### {#design-sender-adaptor-transfer} @@ -2552,7 +3178,9 @@ execution::sender auto transfer( );
-Returns a sender describing the transition from the execution agent of the input sender to the execution agent of the target scheduler. See [[#design-transitions]]. +Returns a sender describing the transition from the execution agent of the input +sender to the execution agent of the target scheduler. See +[[#design-transitions]].
 execution::scheduler auto cpu_sched = get_system_thread_pool().scheduler();
@@ -2574,9 +3202,12 @@ execution::sender auto then(
 );
 
-`then` returns a sender describing the task graph described by the input sender, with an added node of invoking the provided function with the values [=send|sent=] by the input sender as arguments. +`then` returns a sender describing the task graph described by the input sender, +with an added node of invoking the provided function with the values +[=send|sent=] by the input sender as arguments. -`then` is **guaranteed** to not begin executing `function` until the returned sender is started. +`then` is **guaranteed** to not begin executing `function` until the returned +sender is started.
 execution::sender auto input = get_input();
@@ -2587,7 +3218,8 @@ execution::sender auto snd = execution::then(input, [](auto... args) {
 // followed by printing all of the values sent by pred
 
-This adaptor is included as it is necessary for writing any sender code that actually performs a useful function. +This adaptor is included as it is necessary for writing any sender code that +actually performs a useful function. ### `execution::upon_*` ### {#design-sender-adaptor-upon} @@ -2603,7 +3235,9 @@ execution::sender auto upon_stopped( );
-`upon_error` and `upon_stopped` are similar to `then`, but where `then` works with values sent by the input sender, `upon_error` works with errors, and `upon_stopped` is invoked when the "stopped" signal is sent. +`upon_error` and `upon_stopped` are similar to `then`, but where `then` works +with values sent by the input sender, `upon_error` works with errors, and +`upon_stopped` is invoked when the "stopped" signal is sent. ### `execution::let_*` ### {#design-sender-adaptor-let} @@ -2624,12 +3258,21 @@ execution::sender auto let_stopped( );
-`let_value` is very similar to `then`: when it is started, it invokes the provided function with the values [=send|sent=] by the input sender as arguments. However, where the sender returned from `then` sends exactly what that function ends up returning - -`let_value` requires that the function return a sender, and the sender returned by `let_value` sends the values sent by the sender returned from the callback. This is similar to the notion of "future unwrapping" in future/promise-based frameworks. +`let_value` is very similar to `then`: when it is started, it invokes the +provided function with the values [=send|sent=] by the input sender as +arguments. However, where the sender returned from `then` sends exactly what +that function ends up returning - +`let_value` requires that the function return a sender, and the sender returned +by `let_value` sends the values sent by the sender returned from the callback. +This is similar to the notion of "future unwrapping" in future/promise-based +frameworks. -`let_value` is **guaranteed** to not begin executing `function` until the returned sender is started. +`let_value` is **guaranteed** to not begin executing `function` until the +returned sender is started. -`let_error` and `let_stopped` are similar to `let_value`, but where `let_value` works with values sent by the input sender, `let_error` works with errors, and `let_stopped` is invoked when the "stopped" signal is sent. +`let_error` and `let_stopped` are similar to `let_value`, but where `let_value` +works with values sent by the input sender, `let_error` works with errors, and +`let_stopped` is invoked when the "stopped" signal is sent. ### `execution::on` ### {#design-sender-adaptor-on} @@ -2640,7 +3283,10 @@ execution::sender auto on( );
-Returns a sender which, when started, will start the provided sender on an execution agent belonging to the execution resource associated with the provided scheduler. This returned sender has no [=completion scheduler|completion schedulers=]. +Returns a sender which, when started, will start the provided sender on an +execution agent belonging to the execution resource associated with the provided +scheduler. This returned sender has no [=completion scheduler|completion +schedulers=]. ### `execution::into_variant` ### {#design-sender-adaptor-into_variant} @@ -2650,7 +3296,10 @@ execution::sender auto into_variant( );
-Returns a sender which sends a variant of tuples of all the possible sets of types sent by the input sender. Senders can send multiple sets of values depending on runtime conditions; this is a helper function that turns them into a single variant value. +Returns a sender which sends a variant of tuples of all the possible sets of +types sent by the input sender. Senders can send multiple sets of values +depending on runtime conditions; this is a helper function that turns them into +a single variant value. ### `execution::stopped_as_optional` ### {#design-sender-adaptor-stopped_as_optional} @@ -2660,7 +3309,9 @@ execution::sender auto stopped_as_optional( );
-Returns a sender that maps the value channel from a `T` to an `optional>`, and maps the stopped channel to a value of an empty `optional>`. +Returns a sender that maps the value channel from a `T` to an +`optional>`, and maps the stopped channel to a value of an empty +`optional>`. ### `execution::stopped_as_error` ### {#design-sender-adaptor-stopped_as_error} @@ -2684,14 +3335,23 @@ execution::sender auto bulk( );
-Returns a sender describing the task of invoking the provided function with every index in the provided shape along with the values sent by the input sender. The returned sender completes once all invocations have completed, or an error has occurred. If it completes -by sending values, they are equivalent to those sent by the input sender. +Returns a sender describing the task of invoking the provided function with +every index in the provided shape along with the values sent by the input +sender. The returned sender completes once all invocations have completed, or an +error has occurred. If it completes by sending values, they are equivalent to +those sent by the input sender. -No instance of `function` will begin executing until the returned sender is started. Each invocation of `function` runs in an execution agent whose forward progress guarantees are determined by the scheduler on which they are run. All agents created by a single use -of `bulk` execute with the same guarantee. The number of execution agents used by `bulk` is not specified. This allows a scheduler to execute some invocations of the `function` in parallel. +No instance of `function` will begin executing until the returned sender is +started. Each invocation of `function` runs in an execution agent whose forward +progress guarantees are determined by the scheduler on which they are run. All +agents created by a single use of `bulk` execute with the same guarantee. The +number of execution agents used by `bulk` is not specified. This allows a +scheduler to execute some invocations of the `function` in parallel. -In this proposal, only integral types are used to specify the shape of the bulk section. We expect that future papers may wish to explore extensions of the interface to explore additional kinds of shapes, such as multi-dimensional grids, that are commonly used for -parallel computing tasks. +In this proposal, only integral types are used to specify the shape of the bulk +section. We expect that future papers may wish to explore extensions of the +interface to explore additional kinds of shapes, such as multi-dimensional +grids, that are commonly used for parallel computing tasks. ### `execution::split` ### {#design-sender-adaptor-split} @@ -2699,7 +3359,9 @@ parallel computing tasks. execution::sender auto split(execution::sender auto sender); -If the provided sender is a multi-shot sender, returns that sender. Otherwise, returns a multi-shot sender which sends values equivalent to the values sent by the provided sender. See [[#design-shot]]. +If the provided sender is a multi-shot sender, returns that sender. Otherwise, +returns a multi-shot sender which sends values equivalent to the values sent by +the provided sender. See [[#design-shot]]. ### `execution::when_all` ### {#design-sender-adaptor-when_all} @@ -2713,9 +3375,18 @@ execution::sender auto when_all_with_variant( ); -`when_all` returns a sender that completes once all of the input senders have completed. It is constrained to only accept senders that can complete with a single set of values (_i.e._, it only calls one overload of `set_value` on its receiver). The values sent by this sender are the values sent by each of the input senders, in order of the arguments passed to `when_all`. It completes inline on the execution resource on which the last input sender completes, unless stop is requested before `when_all` is started, in which case it completes inline within the call to `start`. +`when_all` returns a sender that completes once all of the input senders have +completed. It is constrained to only accept senders that can complete with a +single set of values (_i.e._, it only calls one overload of `set_value` on its +receiver). The values sent by this sender are the values sent by each of the +input senders, in order of the arguments passed to `when_all`. It completes +inline on the execution resource on which the last input sender completes, +unless stop is requested before `when_all` is started, in which case it +completes inline within the call to `start`. -`when_all_with_variant` does the same, but it adapts all the input senders using `into_variant`, and so it does not constrain the input arguments as `when_all` does. +`when_all_with_variant` does the same, but it adapts all the input senders using +`into_variant`, and so it does not constrain the input arguments as `when_all` +does. The returned sender has no [=completion scheduler|completion schedulers=]. @@ -2744,21 +3415,30 @@ execution::sender auto ensure_started( ); -Once `ensure_started` returns, it is known that the provided sender has been [=connect|connected=] and `start` has been called on the resulting operation state (see [[#design-states]]); in other words, the work described by the provided sender has been submitted -for execution on the appropriate execution resources. Returns a sender which completes when the provided sender completes and sends values equivalent to those of the provided sender. - -If the returned sender is destroyed before `execution::connect()` is called, or if `execution::connect()` is called but the -returned operation-state is destroyed before `execution::start()` is called, then a stop-request is sent to the eagerly launched -operation and the operation is detached and will run to completion in the background. Its result will be discarded when it -eventually completes. - -Note that the application will need to make sure that resources are kept alive in the case that the operation detaches. -e.g. by holding a `std::shared_ptr` to those resources or otherwise having some out-of-band way to signal completion of +Once `ensure_started` returns, it is known that the provided sender has been +[=connect|connected=] and `start` has been called on the resulting operation +state (see [[#design-states]]); in other words, the work described by the +provided sender has been submitted +for execution on the appropriate execution resources. Returns a sender which +completes when the provided sender completes and sends values equivalent to +those of the provided sender. + +If the returned sender is destroyed before `execution::connect()` is called, or +if `execution::connect()` is called but the returned operation-state is +destroyed before `execution::start()` is called, then a stop-request is sent to +the eagerly launched operation and the operation is detached and will run to +completion in the background. Its result will be discarded when it eventually +completes. + +Note that the application will need to make sure that resources are kept alive +in the case that the operation detaches. e.g. by holding a `std::shared_ptr` to +those resources or otherwise having some out-of-band way to signal completion of the operation so that resource release can be sequenced after the completion. ## User-facing sender consumers ## {#design-sender-consumers} -A [=sender consumer=] is an algorithm that takes one or more senders, which it may `execution::connect`, as parameters, and does not return a sender. +A [=sender consumer=] is an algorithm that takes one or more senders, which it +may `execution::connect`, as parameters, and does not return a sender. ### `execution::start_detached` ### {#design-sender-consumer-start_detached} @@ -2768,7 +3448,8 @@ void start_detached( ); -Like `ensure_started`, but does not return a value; if the provided sender sends an error instead of a value, `std::terminate` is called. +Like `ensure_started`, but does not return a value; if the provided sender sends +an error instead of a value, `std::terminate` is called. ### `this_thread::sync_wait` ### {#design-sender-consumer-sync_wait} @@ -2779,24 +3460,44 @@ auto sync_wait( -> std::optional<std::tuple<values-sent-by(sender)>>; -`this_thread::sync_wait` is a sender consumer that submits the work described by the provided sender for execution, similarly to `ensure_started`, except that it blocks the current `std::thread` or thread of `main` until the work is completed, and returns -an optional tuple of values that were sent by the provided sender on its completion of work. Where [[#design-sender-factory-schedule]] and [[#design-sender-factory-just]] are meant to enter the domain of senders, `sync_wait` is meant to exit the domain of -senders, retrieving the result of the task graph. - -If the provided sender sends an error instead of values, `sync_wait` throws that error as an exception, or rethrows the original exception if the error is of type `std::exception_ptr`. - -If the provided sender sends the "stopped" signal instead of values, `sync_wait` returns an empty optional. - -For an explanation of the `requires` clause, see [[#design-typed]]. That clause also explains another sender consumer, built on top of `sync_wait`: `sync_wait_with_variant`. - -Note: This function is specified inside `std::this_thread`, and not inside `execution`. This is because `sync_wait` has to block the current execution agent, but determining what the current execution agent is is not reliable. Since the standard -does not specify any functions on the current execution agent other than those in `std::this_thread`, this is the flavor of this function that is being proposed. If C++ ever obtains fibers, for instance, we expect that a variant of this function called -`std::this_fiber::sync_wait` would be provided. We also expect that runtimes with execution agents that use different synchronization mechanisms than `std::thread`'s will provide their own flavors of `sync_wait` as well (assuming their execution agents have the means +`this_thread::sync_wait` is a sender consumer that submits the work described by +the provided sender for execution, similarly to `ensure_started`, except that it +blocks the current `std::thread` or thread of `main` until the work is +completed, and returns an optional tuple of values that were sent by the +provided sender on its completion of work. Where +[[#design-sender-factory-schedule]] and [[#design-sender-factory-just]] are +meant to enter the domain of senders, `sync_wait` is meant to exit +the domain of senders, retrieving the result of the task graph. + +If the provided sender sends an error instead of values, `sync_wait` throws that +error as an exception, or rethrows the original exception if the error is of +type `std::exception_ptr`. + +If the provided sender sends the "stopped" signal instead of values, `sync_wait` +returns an empty optional. + +For an explanation of the `requires` clause, see [[#design-typed]]. That clause +also explains another sender consumer, built on top of `sync_wait`: +`sync_wait_with_variant`. + +Note: This function is specified inside `std::this_thread`, and not inside +`execution`. This is because `sync_wait` has to block the current +execution agent, but determining what the current execution agent is is not +reliable. Since the standard does not specify any functions on the current +execution agent other than those in `std::this_thread`, this is the flavor of +this function that is being proposed. If C++ ever obtains fibers, for instance, +we expect that a variant of this function called `std::this_fiber::sync_wait` +would be provided. We also expect that runtimes with execution agents that use +different synchronization mechanisms than `std::thread`'s will provide their own +flavors of `sync_wait` as well (assuming their execution agents have the means to block in a non-deadlock manner). ## `execution::execute` ## {#design-execute} -In addition to the three categories of functions presented above, we also propose to include a convenience function for fire-and-forget eager one-way submission of an invocable to a scheduler, to fulfil the role of one-way executors from P0443. +In addition to the three categories of functions presented above, we also +propose to include a convenience function for fire-and-forget eager one-way +submission of an invocable to a scheduler, to fulfil the role of one-way +executors from P0443.
 void execution::execute(
@@ -2817,7 +3518,8 @@ execution::start_detached(work);
 
 ## Receivers serve as glue between senders ## {#design-receivers}
 
-A [=receiver=] is a callback that supports more than one channel. In fact, it supports three of them:
+A [=receiver=] is a callback that supports more than one channel. In fact, it
+supports three of them:
 
 * `set_value`, which is the moral equivalent of an `operator()` or a function
     call, which signals successful completion of the operation its execution
@@ -2830,31 +3532,44 @@ A [=receiver=] is a callback that supports more than one channel. In fact, it su
     to indicate that the operation stopped early, typically because it was asked
     to do so because the result is no longer needed.
 
-Once an async operation has been started exactly one of these functions must be invoked
-on a receiver before it is destroyed.
+Once an async operation has been started exactly one of these functions must be
+invoked on a receiver before it is destroyed.
 
 While the receiver interface may look novel, it is in fact very similar to the
 interface of `std::promise`, which provides the first two signals as `set_value`
 and `set_exception`, and it's possible to emulate the third channel with
 lifetime management of the promise.
 
-Receivers are not a part of the end-user-facing API of this proposal; they are necessary to allow unrelated senders communicate with each other, but the only users who will interact with receivers directly are authors of senders.
+Receivers are not a part of the end-user-facing API of this proposal; they are
+necessary to allow unrelated senders communicate with each other, but the only
+users who will interact with receivers directly are authors of senders.
 
 Receivers are what is passed as the second argument to [[#design-connect]].
 
 ## Operation states represent work ## {#design-states}
 
-An [=operation state=] is an object that represents work. Unlike senders, it is not a chaining mechanism; instead, it is a concrete object that packages the work described by a full sender chain, ready to be executed. An operation state is neither movable nor
-copyable, and its interface consists of a single algorithm: `start`, which serves as the submission point of the work represented by a given operation state.
+An [=operation state=] is an object that represents work. Unlike senders, it is
+not a chaining mechanism; instead, it is a concrete object that packages the
+work described by a full sender chain, ready to be executed. An operation state
+is neither movable nor copyable, and its interface consists of a single
+algorithm: `start`, which serves as the submission point of the work represented
+by a given operation state.
 
-Operation states are not a part of the user-facing API of this proposal; they are necessary for implementing sender consumers like `execution::ensure_started` and `this_thread::sync_wait`, and the knowledge of them is necessary to implement senders, so the only users who will
-interact with operation states directly are authors of senders and authors of sender algorithms.
+Operation states are not a part of the user-facing API of this proposal; they
+are necessary for implementing sender consumers like `execution::ensure_started`
+and `this_thread::sync_wait`, and the knowledge of them is necessary to
+implement senders, so the only users who will interact with operation states
+directly are authors of senders and authors of sender algorithms.
 
-The return value of [[#design-connect]] must satisfy the operation state concept.
+The return value of [[#design-connect]] must satisfy the operation state
+concept.
 
 ## `execution::connect` ## {#design-connect}
 
-`execution::connect` is a customization point which [=connects=] senders with receivers, resulting in an operation state that will ensure that if `start` is called that one of the completion operations will be called on the receiver passed to `connect`.
+`execution::connect` is a customization point which [=connects=] senders with
+receivers, resulting in an operation state that will ensure that if `start` is
+called that one of the completion operations will be called on the receiver
+passed to `connect`.
 
 
 execution::sender auto snd = some input sender;
@@ -2872,18 +3587,31 @@ execution::start(state);
 
 ## Sender algorithms are customizable ## {#design-customization}
 
-Senders being able to advertise what their [=completion schedulers=] are fulfills one of the promises of senders: that of being able to customize an implementation of a sender algorithm based on what scheduler any work it depends on will complete on.
+Senders being able to advertise what their [=completion schedulers=] are
+fulfills one of the promises of senders: that of being able to customize an
+implementation of a sender algorithm based on what scheduler any work it depends
+on will complete on.
 
-The simple way to provide customizations for functions like `then`, that is for [=sender adaptors=] and [=sender consumers=], is to follow the customization scheme that has been adopted for C++20 ranges library; to do that, we would define
-the expression `execution::then(sender, invocable)` to be equivalent to:
+The simple way to provide customizations for functions like `then`, that is for
+[=sender adaptors=] and [=sender consumers=], is to follow the customization
+scheme that has been adopted for C++20 ranges library; to do that, we would
+define the expression `execution::then(sender, invocable)` to be equivalent to:
 
   1. `sender.then(invocable)`, if that expression is well-formed; otherwise
-  2. `then(sender, invocable)`, performed in a context where this call always performs ADL, if that expression is well-formed; otherwise
-  3. a default implementation of `then`, which returns a sender adaptor, and then define the exact semantics of said adaptor.
-
-However, this definition is problematic. Imagine another sender adaptor, `bulk`, which is a structured abstraction for a loop over an index space. Its default implementation is just a for loop. However, for accelerator runtimes like CUDA, we would like sender algorithms
-like `bulk` to have specialized behavior, which invokes a kernel of more than one thread (with its size defined by the call to `bulk`); therefore, we would like to customize `bulk` for CUDA senders to achieve this. However, there's no reason for CUDA kernels to
-necessarily customize the `then` sender adaptor, as the generic implementation is perfectly sufficient. This creates a problem, though; consider the following snippet:
+  2. `then(sender, invocable)`, performed in a context where this call always
+      performs ADL, if that expression is well-formed; otherwise
+  3. a default implementation of `then`, which returns a sender adaptor, and
+      then define the exact semantics of said adaptor.
+
+However, this definition is problematic. Imagine another sender adaptor, `bulk`,
+which is a structured abstraction for a loop over an index space. Its default
+implementation is just a for loop. However, for accelerator runtimes like CUDA,
+we would like sender algorithms like `bulk` to have specialized behavior, which
+invokes a kernel of more than one thread (with its size defined by the call to
+`bulk`); therefore, we would like to customize `bulk` for CUDA senders to
+achieve this. However, there's no reason for CUDA kernels to necessarily
+customize the `then` sender adaptor, as the generic implementation is perfectly
+sufficient. This creates a problem, though; consider the following snippet:
 
 
 execution::scheduler auto cuda_sch = cuda_scheduler{};
@@ -2900,8 +3628,10 @@ execution::sender auto next = execution::then(cuda_sch, []{ return 1; });
 execution::sender auto kernel_sender = execution::bulk(next, shape, [](int i){ ... });
 
-How can we specialize the `bulk` sender adaptor for our wrapped `schedule_sender`? Well, here's one possible approach, taking advantage of ADL (and the fact that the definition of "associated namespace" also recursively enumerates the associated namespaces of all template -parameters of a type): +How can we specialize the `bulk` sender adaptor for our wrapped +`schedule_sender`? Well, here's one possible approach, taking advantage of ADL +(and the fact that the definition of "associated namespace" also recursively +enumerates the associated namespaces of all template parameters of a type):
 namespace cuda::for_adl_purposes {
@@ -2921,208 +3651,237 @@ execution::sender auto bulk(
 } // namespace cuda::for_adl_purposes
 
-However, if the input sender is not just a `then_sender_adaptor` like in the example above, but another sender that overrides `bulk` by itself, as a member function, because its author believes they know an optimization for bulk - the specialization above will no -longer be selected, because a member function of the first argument is a better match than the ADL-found overload. - -This means that well-meant specialization of sender algorithms that are entirely scheduler-agnostic can have negative consequences. -The scheduler-specific specialization - which is essential for good performance on platforms providing specialized ways to launch certain sender algorithms - would not be selected in such cases. -But it's really the scheduler that should control the behavior of sender algorithms when a non-default implementation exists, not the sender. Senders merely describe work; schedulers, however, are the handle to the -runtime that will eventually execute said work, and should thus have the final say in *how* the work is going to be executed. - -Therefore, we are proposing the following customization scheme (also modified to take [[#design-dispatch]] into account): the expression `execution::(sender, args...)`, for any given sender algorithm that accepts a sender as its first argument, should be -equivalent to: - - 1. tag_invoke(<sender-algorithm>, get_completion_scheduler<Tag>(get_env(sender)), sender, args...), if that expression is well-formed; otherwise - 2. `tag_invoke(, sender, args...)`, if that expression is well-formed; otherwise - 4. a default implementation, if there exists a default implementation of the given sender algorithm. - -where Tag is one of `set_value`, `set_error`, or `set_stopped`. For most sender algorithms, the completion scheduler for `set_value` would be used, but for some (like `upon_error` or `let_stopped`), one of the others would be used. - -For sender algorithms which accept concepts other than `sender` as their first argument, we propose that the customization scheme remains as it has been in [[P0443R14]] so far, except it should also use `tag_invoke`. +However, if the input sender is not just a `then_sender_adaptor` like in the +example above, but another sender that overrides `bulk` by itself, as a member +function, because its author believes they know an optimization for bulk - the +specialization above will no longer be selected, because a member function of +the first argument is a better match than the ADL-found overload. + +This means that well-meant specialization of sender algorithms that are entirely +scheduler-agnostic can have negative consequences. The scheduler-specific +specialization - which is essential for good performance on platforms providing +specialized ways to launch certain sender algorithms - would not be selected in +such cases. But it's really the scheduler that should control the behavior of +sender algorithms when a non-default implementation exists, not the sender. +Senders merely describe work; schedulers, however, are the handle to the runtime +that will eventually execute said work, and should thus have the final say in +*how* the work is going to be executed. + +Therefore, we are proposing the following customization scheme: the expression +`execution::(sender, args...)`, for any given sender algorithm +that accepts a sender as its first argument, should do the following: + + 1. Create a sender that implements the default implementation of the sender + algorithm. That sender is tuple-like; it can be destructured into its + constituent parts: algorithm tag, data, and child sender(s). + + 2. We query the child sender for its *domain*. A **domain** is a tag type + associated with the scheduler that the child sender will complete on. + If there are multiple child senders, we query all of them for their + domains and require that they all be the same. + + 3. We use the domain to dispatch to a `transform_sender` customization, which + accepts the sender and optionally performs a domain-specific + transformation on it. This customization is expected to return a new + sender, which will be returned from `` in place of the + original sender. ## Sender adaptors are lazy ## {#design-laziness} -Contrary to early revisions of this paper, we propose to make all sender adaptors perform strictly lazy submission, unless specified otherwise (the one notable exception in this paper is [[#design-sender-adaptor-ensure_started]], whose sole purpose is to start an -input sender). +Contrary to early revisions of this paper, we propose to make all sender +adaptors perform strictly lazy submission, unless specified otherwise (the one +notable exception in this paper is [[#design-sender-adaptor-ensure_started]], +whose sole purpose is to start an input sender). - Strictly lazy submission means that there is a guarantee that no work is submitted to an execution resource before a receiver is connected to a sender, and `execution::start` is called on the resulting operation state. +Strictly lazy submission means that there is a guarantee +that no work is submitted to an execution resource before a receiver is +connected to a sender, and `execution::start` is called on the resulting +operation state. ## Lazy senders provide optimization opportunities ## {#design-fusion} -Because lazy senders fundamentally *describe* work, instead of describing or representing the submission of said work to an execution resource, and thanks to the flexibility of the customization of most sender algorithms, they provide an opportunity for fusing -multiple algorithms in a sender chain together, into a single function that can later be submitted for execution by an execution resource. There are two ways this can happen. - -The first (and most common) way for such optimizations to happen is thanks to the structure of the implementation: because all the work is done within callbacks invoked on the completion of an earlier sender, recursively up to the original source of computation, -the compiler is able to see a chain of work described using senders as a tree of tail calls, allowing for inlining and removal of most of the sender machinery. In fact, when work is not submitted to execution resources outside of the current thread of execution, -compilers are capable of removing the senders abstraction entirely, while still allowing for composition of functions across different parts of a program. - -The second way for this to occur is when a sender algorithm is specialized for a specific set of arguments. For instance, we expect that, for senders which are known to have been started already, [[#design-sender-adaptor-ensure_started]] will be an identity transformation, -because the sender algorithm will be specialized for such senders. Similarly, an implementation could recognize two subsequent [[#design-sender-adaptor-bulk]]s of compatible shapes, and merge them together into a single submission of a GPU kernel. +Because lazy senders fundamentally *describe* work, instead of describing or +representing the submission of said work to an execution resource, and thanks to +the flexibility of the customization of most sender algorithms, they provide an +opportunity for fusing multiple algorithms in a sender chain together, into a +single function that can later be submitted for execution by an execution +resource. There are two ways this can happen. + +The first (and most common) way for such optimizations to happen is thanks to +the structure of the implementation: because all the work is done within +callbacks invoked on the completion of an earlier sender, recursively up to the +original source of computation, the compiler is able to see a chain of work +described using senders as a tree of tail calls, allowing for inlining and +removal of most of the sender machinery. In fact, when work is not submitted to +execution resources outside of the current thread of execution, compilers are +capable of removing the senders abstraction entirely, while still allowing for +composition of functions across different parts of a program. + +The second way for this to occur is when a sender algorithm is specialized for a +specific set of arguments. For instance, we expect that, for senders which are +known to have been started already, [[#design-sender-adaptor-ensure_started]] +will be an identity transformation, because the sender algorithm will be +specialized for such senders. Similarly, an implementation could recognize two +subsequent [[#design-sender-adaptor-bulk]]s of compatible shapes, and merge them +together into a single submission of a GPU kernel. ## Execution resource transitions are two-step ## {#design-transition-details} -Because `execution::transfer` takes a sender as its first argument, it is not actually directly customizable by the target scheduler. This is by design: the target scheduler may not know how to transition from a scheduler such as a CUDA scheduler; -transitioning away from a GPU in an efficient manner requires making runtime calls that are specific to the GPU in question, and the same is usually true for other kinds of accelerators too (or for scheduler running on remote systems). To avoid this problem, -specialized schedulers like the ones mentioned here can still hook into the transition mechanism, and inject a sender which will perform a transition to the regular CPU execution resource, so that any sender can be attached to it. - -This, however, is a problem: because customization of sender algorithms must be controlled by the scheduler they will run on (see [[#design-customization]]), the type of the sender returned from `transfer` must be controllable by the target scheduler. Besides, the target -scheduler may itself represent a specialized execution resource, which requires additional work to be performed to transition to it. GPUs and remote node schedulers are once again good examples of such schedulers: executing code on their execution resources -requires making runtime API calls for work submission, and quite possibly for the data movement of the values being sent by the input sender passed into `transfer`. - -To allow for such customization from both ends, we propose the inclusion of a secondary transitioning sender adaptor, called `schedule_from`. This adaptor is a form of `schedule`, but takes an additional, second argument: the input sender. This adaptor is not -meant to be invoked manually by the end users; they are always supposed to invoke `transfer`, to ensure that both schedulers have a say in how the transitions are made. Any scheduler that specializes `transfer(snd, sch)` shall ensure that the -return value of their customization is equivalent to `schedule_from(sch, snd2)`, where `snd2` is a successor of `snd` that sends values equivalent to those sent by `snd`. - -The default implementation of `transfer(snd, sched)` is `schedule_from(sched, snd)`. +Because `execution::transfer` takes a sender as its first argument, it is not +actually directly customizable by the target scheduler. This is by design: the +target scheduler may not know how to transition from a scheduler such as +a CUDA scheduler; transitioning away from a GPU in an efficient manner requires +making runtime calls that are specific to the GPU in question, and the same is +usually true for other kinds of accelerators too (or for scheduler running on +remote systems). To avoid this problem, specialized schedulers like the ones +mentioned here can still hook into the transition mechanism, and inject a sender +which will perform a transition to the regular CPU execution resource, so that +any sender can be attached to it. + +This, however, is a problem: because customization of sender algorithms must be +controlled by the scheduler they will run on (see [[#design-customization]]), +the type of the sender returned from `transfer` must be controllable by the +target scheduler. Besides, the target scheduler may itself represent a +specialized execution resource, which requires additional work to be performed +to transition to it. GPUs and remote node schedulers are once again good +examples of such schedulers: executing code on their execution resources +requires making runtime API calls for work submission, and quite possibly for +the data movement of the values being sent by the input sender passed into +`transfer`. + +To allow for such customization from both ends, we propose the inclusion of a +secondary transitioning sender adaptor, called `schedule_from`. This adaptor is +a form of `schedule`, but takes an additional, second argument: the input +sender. This adaptor is not meant to be invoked manually by the end users; they +are always supposed to invoke `transfer`, to ensure that both schedulers have a +say in how the transitions are made. Any scheduler that specializes +`transfer(snd, sch)` shall ensure that the return value of their customization +is equivalent to `schedule_from(sch, snd2)`, where `snd2` is a successor of +`snd` that sends values equivalent to those sent by `snd`. + +The default implementation of `transfer(snd, sched)` is `schedule_from(sched, +snd)`. ## All senders are typed ## {#design-typed} -All senders must advertise the types they will [=send=] when they complete. -This is necessary for a number of features, and writing code in a way that's -agnostic of whether an input sender is typed or not in common sender adaptors -such as `execution::then` is hard. - -The mechanism for this advertisement is similar to the one in [[P0443R14]]; the -way to query the types is through `completion_signatures_of_t::value_types`. - -`completion_signatures_of_t::value_types` is a template that takes two -arguments: one is a tuple-like template, the other is a variant-like template. -The tuple-like argument is required to represent senders sending more than one -value (such as `when_all`). The variant-like argument is required to represent -senders that choose which specific values to send at runtime. - -There's a choice made in the specification of -[[#design-sender-consumer-sync_wait]]: it returns a tuple of values sent by the -sender passed to it, wrapped in `std::optional` to handle the `set_stopped` -signal. However, this assumes that those values can be represented as a tuple, -like here: +All senders must advertise the types they will send when they complete. There +are many sender adaptors that need this information. Even just transitioning +from one execution context to another requires temporarily storing the async +result data so it can be propagated in the new execution context. Doing that +efficiently requires knowing the type of the data. + +The mechanism a sender uses to advertise its completions is the +`get_completion_signatures` customization point, which takes an environment and +must return a specialization of the `execution::completion_signatures` class +template. The template parameters of `execution::completion_signatures` is a +list of function types that represent the completion operations of the sender. +for example, the type `execution::set_value_t(size_t, const char*)` indicates +that the sender can complete successfully by passing a `size_t` and a `const +char*` to the receiver's `set_value` function. + +This proposal includes utilities for parsing and manipulating the list of a +sender's completion signatures. For instance, `values_of_t` is a template alias +for accessing a sender's value completions. It takes a sender, an environment, +and two variadic template template parameters: a tuple-like template and a +variant-like template. You can get the value completions of `S` and `Env` with +value_types_of_t<S, Env, tuple-like, +variant-like>. For example, for a sender that can complete +successfully with either `Ts...` or `Us...`, `value_types_of_t` would name the type `std::variant, +std::tuple>`. + +## Customization points ## {#design-dispatch} + +Earlier versions of this paper used a dispatching technique known as +[`tag_invoke`](https://wg21.link/P1895) to allow for customization of basis +operations and sender algorithms. This technique used private friend functions +named "`tag_invoke`" that are found by argument-dependent look-up. The +`tag_invoke` overloads are distinguished from each other by their first +argument, which is the type of the customization point object being customized. +For instance, to customize the `execution::set_value` operation, a receiver type +might do the following:
-execution::sender auto sends_1 = ...;
-execution::sender auto sends_2 = ...;
-execution::sender auto sends_3 = ...;
-
-auto [a, b, c] = this_thread::sync_wait(
-    execution::when_all(
-        sends_1,
-        sends_2,
-        sends_3)
-    | execution::transfer(
-        execution::get_completion_scheduler<execution::set_value_t>(get_env(sends_1))),
-    ).value();
-// a == 1
-// b == 2
-// c == 3
-
- -This works well for senders that always send the same set of arguments. If we ignore the possibility of having a sender that sends different sets of arguments into a receiver, we can specify the "canonical" (i.e. required to be followed by all senders) form of -`value_types` of a sender which sends `Types...` to be as follows: +struct my_receiver { + friend void tag_invoke(execution::set_value_t, my_receiver&& self, int value) noexcept { + std::cout << "received value: " << value; + } -
-template<template<typename ...> typename TupleLike>
-using value_types = TupleLike;
+  //...
+};
 
-If senders could only ever send one specific set of values, this would probably need to be the required form of `value_types` for all senders; defining it otherwise would cause very weird results and should be considered a bug. - -This matter is somewhat complicated by the fact that (1) `set_value` for receivers can be overloaded and accept different sets of arguments, and (2) senders are allowed to send multiple different sets of values, depending on runtime conditions, the data they -consumed, and so on. To accomodate this, [[P0443R14]] also includes a second template parameter to `value_types`, one that represents a variant-like type. If we permit such senders, we would almost certainly need to require that the canonical form of `value_types` -for *all* senders (to ensure consistency in how they are handled, and to avoid accidentally interpreting a user-provided variant as a sender-provided one) sending the different sets of arguments `Types1...`, `Types2...`, ..., `TypesN...` to be as follows: +The `tag_invoke` technique, although it had its strengths, has been replaced +with a new (or rather, a very old) technique that uses explicit concept opt-ins +and named member functions. For instance, the `execution::set_value` operation +is now customized by defining a member function named `set_value` in the +receiver type. This technique is more explicit and easier to understand than +`tag_invoke`. This is what a receiver author would do to customize +`execution::set_value` now:
-template<
-    template<typename ...> typename TupleLike,
-    template<typename ...> typename VariantLike
->
-using value_types = VariantLike<
-    TupleLike<Types1...>,
-    TupleLike<Types2...>,
-    ...,
-    TupleLike<Types3...>
->;
-
- -This, however, introduces a couple of complications: +struct my_receiver { + using receiver_concept = execution::receiver_t; -1. A `just(1)` sender would also need to follow this structure, so the correct type for storing the value sent by it would be `std::variant>` or some such. This introduces a lot of compile time overhead for the simplest senders, and this overhead - effectively exists in all places in the code where `value_types` is queried, regardless of the tuple-like and variant-like templates passed to it. Such overhead does exist if only the tuple-like parameter exists, but is made much worse by adding this second - wrapping layer. -2. As a consequence of (1): because `sync_wait` needs to store the above type, it can no longer return just a `std::tuple` for `just(1)`; it has to return `std::variant>`. C++ currently does not have an easy way to destructure this; it may get - less awkward with pattern matching, but even then it seems extremely heavyweight to involve variants in this API, and for the purpose of generic code, the kind of the return type of `sync_wait` must be the same across all sender types. - -One possible solution to (2) above is to place a requirement on `sync_wait` that it can only accept senders which send only a single set of values, therefore removing the need for `std::variant` to appear in its API; because of this, we propose to expose both -`sync_wait`, which is a simple, user-friendly version of the sender consumer, but requires that `value_types` have only one possible variant, and `sync_wait_with_variant`, which accepts any sender, but returns an optional whose value type is the variant of all the -possible tuples sent by the input sender: - -
-auto sync_wait_with_variant(
-    execution::sender auto sender
-) -> std::optional<std::variant<
-        std::tuple<values0-sent-by(sender)>,
-        std::tuple<values1-sent-by(sender)>,
-        ...,
-        std::tuple<valuesn-sent-by(sender)>
-    >>;
+  void set_value(int value) && noexcept {
+    std::cout << "received value: " << value;
+  }
 
-auto sync_wait(
-    execution::sender auto sender
-) requires (always-sends-same-values(sender))
-    -> std::optional<std::tuple<values-sent-by(sender)>>;
+  //...
+};
 
-## Ranges-style CPOs vs `tag_invoke` ## {#design-dispatch} - -The contemporary technique for customization in the Standard Library is customization point objects. A customization point object, will it look for member functions and then for nonmember functions with the same name as the customization point, and calls those if -they match. This is the technique used by the C++20 ranges library, and previous executors proposals ([[P0443R14]] and [[P1897R3]]) intended to use it as well. However, it has several unfortunate consequences: - -1. It does not allow for easy propagation of customization points unknown to the adaptor to a wrapped object, which makes writing universal adapter types much harder - and this proposal uses quite a lot of those. - -2. It effectively reserves names globally. Because neither member names nor ADL-found functions can be qualified with a namespace, every customization point object that uses the ranges scheme reserves the name for all types in all namespaces. This is unfortunate - due to the sheer number of customization points already in the paper, but also ones that we are envisioning in the future. It's also a big problem for one of the operations being proposed already: `sync_wait`. We imagine that if, in the future, C++ was to - gain fibers support, we would want to also have `std::this_fiber::sync_wait`, in addition to `std::this_thread::sync_wait`. However, because we would want the names to be the same in both cases, we would need to make the names of the customizations not match the - names of the customization points. This is undesirable. - -This paper proposes to instead use the mechanism described in [[P1895R0]]: `tag_invoke`; the wording for `tag_invoke` has been incorporated into the proposed specification in this paper. - -In short, instead of using globally reserved names, `tag_invoke` uses the type of the customization point object itself as the mechanism to find customizations. It globally reserves only a single name - `tag_invoke` - which itself is used the same way that -ranges-style customization points are used. All other customization points are defined in terms of `tag_invoke`. For example, the customization for `std::this_thread::sync_wait(s)` will call `tag_invoke(std::this_thread::sync_wait, s)`, instead of attempting -to invoke `s.sync_wait()`, and then `sync_wait(s)` if the member call is not valid. +The only exception to this is the customization of queries. There is a need to +build queryable adaptors that can forward and open and unknowable set of queries +to some wrapped object. This is done by defining a member function named +`query` in the adaptor type that takes the query CPO object as its first +(and usually only) argument. A queryable adaptor might look like this: -Using `tag_invoke` has the following benefits: - -1. It reserves only a single global name, instead of reserving a global name for every customization point object we define. +
+template <class Query, class Queryable, class... Args>
+concept query_for =
+  execution::queryable<Queryable> &&
+  requires (const Queryable& o, Args&&... args) {
+    o.query(Query(), (Args&&) args...);
+  };
 
-2. It is possible to propagate customizations to a subobject, because the information of which customization point is being resolved is in the type of an argument, and not in the name of the function:
+template<class Allocator = std::allocator<>,
+         execution::queryable Base = execution::empty_env>
+struct with_allocator {
+  Allocator alloc{};
+  Base base{};
 
-    
-    // forward most customizations to a subobject
-    template<typename Tag, typename ...Args>
-    friend auto tag_invoke(Tag && tag, wrapper & self, Args &&... args) {
-        return std::forward<Tag>(tag)(self.subobject, std::forward<Args>(args)...);
-    }
+  // Forward unknown queries to the wrapped object:
+  template<query_for<Base> Query>
+  decltype(auto) query(Query q) const {
+    return base.query(q);
+  }
 
-    // but override one of them with a specific value
-    friend auto tag_invoke(specific_customization_point_t, wrapper & self) {
-        return self.some_value;
-    }
-    
+ // Specialize the query for the allocator: + Allocator query(execution::get_allocator_t) const { + return alloc; + } +}; +
-3. It is possible to pass those as template arguments to types, because the information of which customization point is being resolved is in the type. Similarly to how [[P0443R14]] defines a polymorphic executor wrapper which accepts a list of properties it - supports, we can imagine scheduler and sender wrappers that accept a list of queries and operations they support. That list can contain the types of the customization point objects, and the polymorphic wrappers can then specialize those customization points on - themselves using `tag_invoke`, dispatching to manually constructed vtables containing pointers to specialized implementations for the wrapped objects. For an example of such a polymorphic wrapper, see - [unifex::any_unique](https://github.com/facebookexperimental/libunifex/blob/1a6fbfc9cc3829356ccbdcf9e8d1f3cc33a6d9e0/include/unifex/any_unique.hpp) - ([example](https://github.com/facebookexperimental/libunifex/blob/1a6fbfc9cc3829356ccbdcf9e8d1f3cc33a6d9e0/examples/any_unique.cpp)). +Customization of sender algorithms such as `execution::then` and +`execution::bulk` are handled differently because they must dispatch based on +where the sender is executing. See the section on [[#design-customization]] for +more information. # Specification # {#spec} Much of this wording follows the wording of [[P0443R14]]. -[[#spec-utilities]] is meant to be a diff relative to the wording of the [utilities] clause of [[N4885]]. This diff applies changes from [[P1895R0]]. +[[#spec-utilities]] is meant to be a diff relative to the wording of the +[utilities] clause of [[N4885]]. This diff applies changes from +[[P1895R0]]. -[[#spec-thread]] is meant to be a diff relative to the wording of the [thread] clause of [[N4885]]. This diff applies changes from [[P2175R0]]. +[[#spec-thread]] is meant to be a diff relative to the wording of the +[thread] clause of [[N4885]]. This diff applies changes from [[P2175R0]]. -[[#spec-execution]] is meant to be added as a new library clause to the working draft of C++. +[[#spec-execution]] is meant to be added as a new library clause to the working +draft of C++. # Exception handling [except] # {#spec-except} @@ -3132,15 +3891,18 @@ Much of this wording follows the wording of [[P0443R14]]. #### The `std::terminate` function [except.terminate] #### {#spec-except.terminate} -
At the end of the bulleted list in the Note in paragraph 1, add a new bullet as follows:
+
At the end of the bulleted list in the Note in paragraph 1, add +a new bullet as follows:
- - when a callback invocation exits via an exception when requesting stop on a `std::stop_source` - or a `std::in_place_stop_source` ([stopsource.mem], [stopsource.inplace.mem]), or in - the constructor of `std::stop_callback` or `std::in_place_stop_callback` - ([stopcallback.cons], [stopcallback.inplace.cons]) when a callback invocation exits - via an exception. + + - when a callback invocation exits via an exception when requesting stop on a + `std::stop_source` or a `std::in_place_stop_source` ([stopsource.mem], + [stopsource.inplace.mem]), or in the constructor of `std::stop_callback` or + `std::in_place_stop_callback` ([stopcallback.cons], + [stopcallback.inplace.cons]) when a callback invocation exits via an + exception.
@@ -3246,7 +4008,8 @@ template<class T, class CB> ### Stop token concepts [thread.stoptoken.concepts] ### {#spec-thread.stoptoken.concepts} -Insert this subclause as a new subclause between Header `` synopsis [thread.stoptoken.syn] and Class `stop_token` [stoptoken]. +Insert this subclause as a new subclause between Header `` synopsis +[thread.stoptoken.syn] and Class `stop_token` [stoptoken].
@@ -3288,21 +4051,31 @@ template<class T> };
-
LWG directed me to replace `T::stop_possible()` with `t.stop_possible()` because -of the recent `constexpr` changes in [[P2280r2|P2280R2]]. However, even with those changes, a nested -requirement like `requires (!t.stop_possible())`, where `t` is an argument in the requirement-parameter-list, is ill-formed according to -[expr.prim.req.nested/p2]: +
LWG directed me to replace `T::stop_possible()` with +`t.stop_possible()` because of the recent `constexpr` changes in +[[P2280r2|P2280R2]]. However, even with those changes, a nested requirement like +`requires (!t.stop_possible())`, where `t` is an argument in the +requirement-parameter-list, is ill-formed according to [expr.prim.req.nested/p2]: -> A local parameter shall only appear as an unevaluated operand within the constraint-expression. +> A local parameter shall only appear as an unevaluated operand within the +> constraint-expression. This is the subject of core issue [[cwg2517|2517]].
-2. Let `t` and `u` be distinct, valid objects of type `T`. The type `T` models `stoppable_token` only if: +2. Let `t` and `u` be distinct, valid objects of type `T`. The type `T` models + `stoppable_token` only if: - 1. If `t.stop_possible()` evaluates to `false` then, if `t` and `u` reference the same logical shared stop state, `u.stop_possible()` shall also subsequently evaluate to `false` and `u.stop_requested()` shall also subsequently evaluate to `false`. + 1. If `t.stop_possible()` evaluates to `false` then, if `t` and `u` + reference the same logical shared stop state, `u.stop_possible()` shall + also subsequently evaluate to `false` and `u.stop_requested()` shall also + subsequently evaluate to `false`. - 2. If `t.stop_requested()` evaluates to `true` then, if `t` and `u` reference the same logical shared stop state, `u.stop_requested()` shall also subsequently evaluate to `true` and `u.stop_possible()` shall also subsequently evaluate to `true`. + 2. If `t.stop_requested()` evaluates to `true` then, if `t` and `u` + reference the same logical shared stop state, `u.stop_requested()` shall + also subsequently evaluate to `true` and `u.stop_possible()` shall also + subsequently evaluate to `true`. 3. Let `t` and `u` be distinct, valid objects of type `T` and let `init` be an object of type `Initializer`. Then for some type `CB`, the type `T` models @@ -3327,21 +4100,31 @@ This is the subject of core issue [[cwg2517|2517]]. registered then `callback` can be invoked on the thread executing `cb`'s constructor. - 2. If `callback` is invoked then, if `t` and `u` reference the same shared stop - state, an evaluation of `u.stop_requested()` will be `true` - if the beginning of the invocation of `callback` + 2. If `callback` is invoked then, if `t` and `u` reference the same + shared stop state, an evaluation of `u.stop_requested()` will be + `true` if the beginning of the invocation of `callback` strongly-happens-before the evaluation of `u.stop_requested()`. - 3. [*Note:* If `t.stop_possible()` evaluates to `false` then the construction of - `cb` is not required to construct and initialize `callback`. *--end note*] + 3. If `t.stop_possible()` evaluates to `false` + then the construction of `cb` is not required to construct and + initialize `callback`. - 3. Construction of a `T::callback_type` instance shall only throw exceptions thrown by the initialization of the `CB` instance from the value of type `Initializer`. + 3. Construction of a `T::callback_type` instance shall only throw + exceptions thrown by the initialization of the `CB` instance from the + value of type `Initializer`. - 4. Destruction of the `T::callback_type` object, `cb`, removes `callback` from the shared stop state such that `callback` will not be invoked after the destructor returns. + 4. Destruction of the `T::callback_type` object, `cb`, removes + `callback` from the shared stop state such that `callback` will not be + invoked after the destructor returns. - 1. If `callback` is currently being invoked on another thread then the destructor of `cb` will block until the invocation of `callback` returns such that the return from the invocation of `callback` strongly-happens-before the destruction of `callback`. + 1. If `callback` is currently being invoked on another thread then the + destructor of `cb` will block until the invocation of `callback` + returns such that the return from the invocation of `callback` + strongly-happens-before the destruction of `callback`. - 2. Destruction of a callback `cb` shall not block on the completion of the invocation of some other callback registered with the same shared stop state. + 2. Destruction of a callback `cb` shall not block on the completion of + the invocation of some other callback registered with the same shared + stop state. @@ -3350,7 +4133,8 @@ This is the subject of core issue [[cwg2517|2517]]. #### General [stoptoken.general] #### {#spec-stoptoken.general} -Modify the synopsis of class `stop_token` in subclause General [stoptoken.general] as follows: +Modify the synopsis of class `stop_token` in subclause General +[stoptoken.general] as follows:
 namespace std {
@@ -3367,11 +4151,15 @@ namespace std {
 
 ### Class `never_stop_token` [stoptoken.never] ### {#spec-stoptoken.never}
 
-Insert a new subclause, Class `never_stop_token` [stoptoken.never], after subclause Class template `stop_callback` [stopcallback], as a new subclause of Stop tokens [thread.stoptoken].
+Insert a new subclause, Class `never_stop_token` [stoptoken.never], after
+subclause Class template `stop_callback` [stopcallback], as a new
+subclause of Stop tokens [thread.stoptoken].
 
 #### General [stoptoken.never.general] #### {#spec-stoptoken.never.general}
 
-1. The class `never_stop_token` provides an implementation of the `unstoppable_token` concept. It provides a stop token interface, but also provides static information that a stop is never possible nor requested.
+1. The class `never_stop_token` provides an implementation of the
+    `unstoppable_token` concept. It provides a stop token interface, but also
+    provides static information that a stop is never possible nor requested.
 
 
 namespace std
@@ -3395,12 +4183,19 @@ namespace std
 
 ### Class `in_place_stop_token` [stoptoken.inplace] ### {#spec-stoptoken.inplace}
 
-Insert a new subclause, Class `in_place_stop_token` [stoptoken.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].
+Insert a new subclause, Class `in_place_stop_token` [stoptoken.inplace],
+after the subclause added above, as a new subclause of Stop tokens
+[thread.stoptoken].
 
 #### General [stoptoken.inplace.general] #### {#spec-stoptoken.inplace.general}
 
-1. The class `in_place_stop_token` provides an interface for querying whether a stop request has been made (`stop_requested`) or can ever be made (`stop_possible`) using an associated `in_place_stop_source` object ([stopsource.inplace]).
-    An `in_place_stop_token` can also be passed to an `in_place_stop_callback` ([stopcallback.inplace]) constructor to register a callback to be called when a stop request has been made from an associated `in_place_stop_source`.
+1. The class `in_place_stop_token` provides an interface for querying whether a
+    stop request has been made (`stop_requested`) or can ever be made
+    (`stop_possible`) using an associated `in_place_stop_source` object
+    ([stopsource.inplace]). An `in_place_stop_token` can also be passed to an
+    `in_place_stop_callback` ([stopcallback.inplace]) constructor to register a
+    callback to be called when a stop request has been made from an associated
+    `in_place_stop_source`.
 
 
 namespace std {
@@ -3439,7 +4234,8 @@ in_place_stop_token() noexcept;
 void swap(stop_token& rhs) noexcept;
 
-2. *Effects*: Exchanges the values of source_ and rhs.source_. +2. *Effects*: Exchanges the values of source_ and + rhs.source_. #### Members [stoptoken.inplace.mem] #### {#spec-stoptoken.inplace.mem} @@ -3447,11 +4243,12 @@ void swap(stop_token& rhs) noexcept; [[nodiscard]] bool stop_requested() const noexcept;
-1. *Effects*: Equivalent to: return source_ != nullptr && source_->stop_requested(); +1. *Effects*: Equivalent to: return source_ != nullptr && + source_->stop_requested(); -2. [*Note*: The behavior of `stop_requested()` is undefined unless the call - strongly happens before the start of the destructor of the associated - `in_place_stop_source`, if any ([basic.life]). --*end note*] +2. The behavior of `stop_requested()` is undefined unless + the call strongly happens before the start of the destructor of the + associated `in_place_stop_source`, if any ([basic.life]).
 [[nodiscard]] bool stop_possible() const noexcept;
@@ -3459,9 +4256,10 @@ void swap(stop_token& rhs) noexcept;
 
 3. *Effects*: Equivalent to: return source_ != nullptr;
 
-4. [*Note*: The behavior of `stop_possible()` is implementation-defined unless
-    the call strongly happens before the end of the storage duration of the
-    associated `in_place_stop_source` object, if any ([basic.stc.general]). --*end note*]
+4. The behavior of `stop_possible()` is
+    implementation-defined unless the call strongly happens before the end of
+    the storage duration of the associated `in_place_stop_source` object, if any
+    ([basic.stc.general]).
 
 #### Non-member functions [stoptoken.inplace.nonmembers] #### {#spec-stoptoken.inplace.nonmembers}
 
@@ -3473,14 +4271,20 @@ friend void swap(in_place_stop_token& x, in_place_stop_token& y) noexcept;
 
 ### Class `in_place_stop_source` [stopsource.inplace] ### {#spec-stopsource.inplace}
 
-Insert a new subclause, Class `in_place_stop_source` [stopsource.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].
+Insert a new subclause, Class `in_place_stop_source`
+[stopsource.inplace], after the subclause added above, as a new subclause
+of Stop tokens [thread.stoptoken].
 
 #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general}
 
-1. The class `in_place_stop_source` implements the semantics of making a stop request, without the need for a dynamic allocation of a shared state.
-    A stop request made on a `in_place_stop_source` object is visible to all associated `in_place_stop_token` ([stoptoken.inplace]) objects.
-    Once a stop request has been made it cannot be withdrawn (a subsequent stop request has no effect).
-    All uses of `in_place_stop_token` objects associated with a given `in_place_stop_source` object must happen before the start of the destructor of that `in_place_stop_source` object.
+1. The class `in_place_stop_source` implements the semantics of making a stop
+    request, without the need for a dynamic allocation of a shared state. A stop
+    request made on a `in_place_stop_source` object is visible to all associated
+    `in_place_stop_token` ([stoptoken.inplace]) objects. Once a stop request has
+    been made it cannot be withdrawn (a subsequent stop request has no effect).
+    All uses of `in_place_stop_token` objects associated with a given
+    `in_place_stop_source` object must happen before the start of the destructor
+    of that `in_place_stop_source` object.
 
 
 namespace std {
@@ -3501,26 +4305,30 @@ namespace std {
 }
 
-2. An instance of `in_place_stop_source` maintains a list of registered callback invocations. - The registration of a callback invocation either succeeds or fails. When an invocation - of a callback is registered, the following happens atomically: +2. An instance of `in_place_stop_source` maintains a list of registered callback + invocations. The registration of a callback invocation either succeeds or + fails. When an invocation of a callback is registered, the following happens + atomically: - - The stop state is checked. If stop has not been requested, the callback invocation is - added to the list of registered callback invocations, and registration has succeeded. + - The stop state is checked. If stop has not been requested, the callback + invocation is added to the list of registered callback invocations, + and registration has succeeded. - - Otherwise, registration has failed. + - Otherwise, registration has failed. - When an invocation of a callback is unregistered, the invocation is atomically removed - from the list of registered callback invocations. The removal is not blocked by the concurrent - execution of another callback invocation in the list. If the callback invocation - being unregistered is currently executing, then: + When an invocation of a callback is unregistered, the invocation is + atomically removed from the list of registered callback invocations. The + removal is not blocked by the concurrent execution of another callback + invocation in the list. If the callback invocation being unregistered is + currently executing, then: - - If the execution of the callback invocation is happening concurrently on another thread, - the completion of the execution strongly happens before ([intro.races]) the end of the - callback's lifetime. + - If the execution of the callback invocation is happening concurrently on + another thread, the completion of the execution strongly happens + before ([intro.races]) the end of the callback's lifetime. - - Otherwise, the execution is happening on the current thread. Removal of the - callback invocation does not block waiting for the execution to complete. + - Otherwise, the execution is happening on the current thread. Removal of + the callback invocation does not block waiting for the execution to + complete. #### Constructors, copy, and assignment [stopsource.inplace.cons] #### {#spec-stopsource.inplace.cons} @@ -3544,16 +4352,20 @@ in_place_stop_source() noexcept; [[nodiscard]] bool stop_requested() const noexcept;
-3. *Returns*: `true` if the stop state inside `*this` has received a stop request; otherwise, `false`. +3. *Returns*: `true` if the stop state inside `*this` has received a stop + request; otherwise, `false`.
 bool request_stop() noexcept;
 
-4. *Effects*: Atomically determines whether the stop state inside `*this` has received a stop request, and if not, makes a stop request. - The determination and making of the stop request are an atomic read-modify-write operation ([intro.races]). - If the request was made, the registered invocations are executed and the evaluations of the invocations are indeterminately sequenced. - If an invocation of a callback exits via an exception then `terminate` is invoked ([except.terminate]). +4. *Effects*: Atomically determines whether the stop state inside `*this` has + received a stop request, and if not, makes a stop request. The determination + and making of the stop request are an atomic read-modify-write operation + ([intro.races]). If the request was made, the registered invocations are + executed and the evaluations of the invocations are indeterminately + sequenced. If an invocation of a callback exits via an exception then + `terminate` is invoked ([except.terminate]). 5. *Postconditions*: `stop_requested()` is `true`. @@ -3561,7 +4373,9 @@ bool request_stop() noexcept; ### Class template `in_place_stop_callback` [stopcallback.inplace] ### {#spec-stopcallback.inplace} -Insert a new subclause, Class template `in_place_stop_callback` [stopcallback.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken]. +Insert a new subclause, Class template `in_place_stop_callback` +[stopcallback.inplace], after the subclause added above, as a new +subclause of Stop tokens [thread.stoptoken]. #### General [stopcallback.inplace.general] #### {#spec-stopcallback.inplace.general} @@ -3592,11 +4406,17 @@ Insert a new subclause, Class template `in_place_stop_callback` [stopcallback }
-2. *Mandates*: `in_place_stop_callback` is instantiated with an argument for the template parameter `Callback` that satisfies both `invocable` and `destructible`. +2. *Mandates*: `in_place_stop_callback` is instantiated with an argument for the + template parameter `Callback` that satisfies both `invocable` and + `destructible`. -3. *Preconditions*: `in_place_stop_callback` is instantiated with an argument for the template parameter `Callback` that models both `invocable` and `destructible`. +3. *Preconditions*: `in_place_stop_callback` is instantiated with an argument + for the template parameter `Callback` that models both `invocable` and + `destructible`. -4. *Recommended practice*: Implementations should use the storage of the `in_place_stop_callback` objects to store the state necessary for their association with an `in_place_stop_source` object. +4. *Recommended practice*: Implementations should use the storage of the + `in_place_stop_callback` objects to store the state necessary for their + association with an `in_place_stop_source` object. #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons} @@ -3610,17 +4430,20 @@ template<class C> 2. *Preconditions*: `Callback` and `C` model `constructible_from`. -3. *Effects*: Initializes callback_ with `std::forward(cb)`. - Any `in_place_stop_source` associated with `st` becomes associated with `*this`. - Registers ([stopsource.inplace.general]) the callback invocation - std::forward<Callback>(callback_)() with the associated - `in_place_stop_source`, if any. If the registration fails, evaluates - the callback invocation. +3. *Effects*: Initializes callback_ with + `std::forward(cb)`. Any `in_place_stop_source` associated with `st` + becomes associated with `*this`. Registers ([stopsource.inplace.general]) + the callback invocation + std::forward<Callback>(callback_)() with the + associated `in_place_stop_source`, if any. If the registration fails, + evaluates the callback invocation. -4. *Throws*: Any exception thrown by the initialization of callback_. +4. *Throws*: Any exception thrown by the initialization of + callback_. -5. *Remarks*: If evaluating std::forward<Callback>(callback_)() - exits via an exception, then `terminate` is invoked ([except.terminate]). +5. *Remarks*: If evaluating + std::forward<Callback>(callback_)() exits via an + exception, then `terminate` is invoked ([except.terminate]).
 ~in_place_stop_callback();
@@ -3720,9 +4543,10 @@ template<class C>
             (!is_array_v<remove_cvref_t<T>>);
         
- 3. For function types `F1` and `F2` denoting `R1(Args1...)` and `R2(Args2...)` - respectively, MATCHING-SIG(F1, F2) is `true` if and only if - `same_as` is `true`. + 3. For function types `F1` and `F2` denoting `R1(Args1...)` and + `R2(Args2...)` respectively, MATCHING-SIG(F1, F2) is + `true` if and only if `same_as` is + `true`. 4. For a subexpression `err`, let `Err` be `decltype((err))` and let AS-EXCEPT-PTR(err) be: @@ -3731,11 +4555,11 @@ template<class C> - *Mandates:* `err != exception_ptr()` is `true` - 2. Otherwise, `make_exception_ptr(system_error(err))` if `decay_t` denotes the type `error_code`, + 2. Otherwise, `make_exception_ptr(system_error(err))` if `decay_t` + denotes the type `error_code`, 3. Otherwise, `make_exception_ptr(err)`. - ## Queries and queryables [exec.queryable] ## {#spec-execution.queryable} ### General [exec.queryable.general] ### {#spec-execution.queryable.general} @@ -3777,11 +4601,11 @@ template<class C> 1. The `queryable` concept specifies the constraints on the types of queryable objects. -2. Let `env` be an object of type `Env`. The type `Env` models `queryable` if for each - callable object q and a pack of subexpressions `args`, - if requires { q(env, args...) } is `true` then - q(env, args...) meets any semantic requirements imposed by - q. +2. Let `env` be an object of type `Env`. The type `Env` models `queryable` if + for each callable object q and a pack of subexpressions + `args`, if requires { q(env, args...) } is `true` then + q(env, args...) meets any semantic requirements imposed + by q. ## Asynchronous operations [async.ops] ## {#spec-execution-async.ops} @@ -4114,22 +4938,26 @@ namespace std::execution { // [exec.snd.transform], sender transformations template<class Domain, sender Sndr, queryable... Env> requires (sizeof...(Env) <= 1) - constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below); + constexpr sender decltype(auto) transform_sender( + Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below); // [exec.snd.transform.env], environment transformations template<class Domain, sender Sndr, queryable Env> - constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept; + constexpr queryable decltype(auto) transform_env( + Domain dom, Sndr&& sndr, Env&& env) noexcept; // [exec.snd.apply], sender algorithm application template<class Domain, class Tag, sender Sndr, class... Args> - constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below); + constexpr decltype(auto) apply_sender( + Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below); // [exec.connect], the connect sender algorithm struct connect_t; inline constexpr connect_t connect{}; template<class Sndr, class Rcvr> - using connect_result_t = decltype(connect(declval<Sndr>(), declval<Rcvr>())); + using connect_result_t = + decltype(connect(declval<Sndr>(), declval<Rcvr>())); // [exec.factories], sender factories struct just_t; @@ -4225,7 +5053,8 @@ namespace std::execution { requires sender_in<Sndr, Env> using transform_completion_signatures_of = transform_completion_signatures< - completion_signatures_of_t<Sndr, Env>, AdditionalSignatures, SetValue, SetError, SetStopped>; + completion_signatures_of_t<Sndr, Env>, + AdditionalSignatures, SetValue, SetError, SetStopped>; // [exec.ctx], execution resources // [exec.run.loop], run_loop @@ -4509,7 +5338,8 @@ enum class forward_progress_guarantee { requires(Sch&& sch) { { schedule(std::forward<Sch>(sch)) } -> sender; { get_completion_scheduler<set_value_t>( - get_env(schedule(std::forward<Sch>(sch)))) } -> same_as<remove_cvref_t<Sch>>; + get_env(schedule(std::forward<Sch>(sch)))) } + -> same_as<remove_cvref_t<Sch>>; } && equality_comparable<remove_cvref_t<Sch>> && copy_constructible<remove_cvref_t<Sch>>; @@ -4580,12 +5410,15 @@ enum class forward_progress_guarantee { }; template<class Rcvr, class Completions> - concept receiver_of = - receiver<Rcvr> && + concept has-completions = // exposition only requires (Completions* completions) { []<valid-completion-for<Rcvr>...Sigs>(completion_signatures<Sigs...>*) {}(completions); }; + + template<class Rcvr, class Completions> + concept receiver_of = + receiver<Rcvr> && has-completions<Rcvr, Completions>;
3. Let `rcvr` be a receiver and let `op_state` be an operation state associated @@ -4748,22 +5581,24 @@ enum class forward_progress_guarantee { constexpr auto completion-domain(const Sndr& sndr) noexcept; - 1. *Effects:* Let COMPL-DOMAIN(T) be the type of the expression - `get_domain(get_completion_scheduler(get_env(sndr)))`. If - COMPL-DOMAIN(set_value_t), + 1. *Effects:* Let COMPL-DOMAIN(T) be the type of the + expression `get_domain(get_completion_scheduler(get_env(sndr)))`. + If COMPL-DOMAIN(set_value_t), COMPL-DOMAIN(set_error_t), and - COMPL-DOMAIN(set_stopped_t) all share a common type - [meta.trans.other] (ignoring those types that are ill-formed), then - completion-domain<Default>(sndr) is a default-constructed - prvalue of that type. - Otherwise, if all of those types are ill-formed, - completion-domain<Default>(sndr) is a default-constructed - prvalue of type `Default`. - Otherwise, completion-domain<Default>(sndr) is ill-formed. + COMPL-DOMAIN(set_stopped_t) all share a common + type [meta.trans.other] (ignoring those types that are ill-formed), + then completion-domain<Default>(sndr) is a + default-constructed prvalue of that type. Otherwise, if all of those + types are ill-formed, + completion-domain<Default>(sndr) is a + default-constructed prvalue of type `Default`. Otherwise, + completion-domain<Default>(sndr) is + ill-formed. 8.
         template<class Tag, class Env, class Default>
-          constexpr decltype(auto) query-with-default(Tag, const Env& env, Default&& value) noexcept(see below);
+          constexpr decltype(auto) query-with-default(
+            Tag, const Env& env, Default&& value) noexcept(see below);
         
1. Let e be the expression `Tag()(env)` if that @@ -4781,8 +5616,8 @@ enum class forward_progress_guarantee { 1. Effects: Equivalent to return Domain(); - where `Domain` is the decayed type of the first of the following - expressions that is well-formed: + where `Domain` is the decayed type of the first of the + following expressions that is well-formed: - `get_domain(get_env(sndr))` @@ -4822,9 +5657,10 @@ enum class forward_progress_guarantee { - `default_domain()`. - The `transfer` algorithm is unique in that it ignores the - execution domain of its predecessor, using only the domain of its - destination scheduler to select a customization. + The `transfer` algorithm is unique in that it + ignores the execution domain of its predecessor, using only the + domain of its destination scheduler to select a + customization. 11.
         template<callable Fun>
@@ -4877,12 +5713,14 @@ enum class forward_progress_guarantee {
           constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
- 1. *Returns:* A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> - where the tag member has been default-initialized and the - data and childn... members have - been direct initialized from their respective forwarded arguments, where - basic-sender is the following exposition-only class template - except as noted below: + 1. *Returns:* A prvalue of type basic-sender<Tag, + decay_t<Data>, decay_t<Child>...> where the + tag member has been default-initialized and the + data and + childn... members have been direct + initialized from their respective forwarded arguments, where + basic-sender is the following exposition-only + class template except as noted below:
               template<class T, class... Us>
@@ -5041,12 +5879,13 @@ enum class forward_progress_guarantee {
         3. It is unspecified whether instances of basic-sender can be
             aggregate initialized.
 
-        4. An expression of type basic-sender is usable as the
-            initializer of a structured binding declaration
-            [dcl.struct.bind].
+        4. An expression of type
+            basic-sender is usable as the initializer of a
+            structured binding declaration [dcl.struct.bind].
 
-        5. The member default-impls::get-attrs is initialized
-            with a callable object equivalent to the following lambda:
+        5. The member default-impls::get-attrs is
+            initialized with a callable object equivalent to the following
+            lambda:
 
               
               [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
@@ -5344,13 +6183,15 @@ enum class forward_progress_guarantee {
 struct default_domain {
   template <sender Sndr, queryable... Env>
       requires (sizeof...(Env) <= 1)
-    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
+    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
+      noexcept(see below);
 
   template <sender Sndr, queryable Env>
     static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
 
   template<class Tag, sender Sndr, class... Args>
-    static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+    static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
+      noexcept(see below);
 };
 
@@ -5359,7 +6200,8 @@ struct default_domain {
 template <sender Sndr, queryable... Env>
     requires (sizeof...(Env) <= 1)
-  constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env) noexcept(see below);
+  constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
+    noexcept(see below);
 
1. Let e be the expression @@ -5386,7 +6228,8 @@ template <sender Sndr, queryable Env>
 template<class Tag, sender Sndr, class... Args>
-  constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+  constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
+    noexcept(see below);
 
7. Let e be the expression @@ -5396,14 +6239,16 @@ template<class Tag, sender Sndr, class... Args> 9. Returns: e. -10. Remarks: The exception specification is equivalent to noexcept(e). +10. Remarks: The exception specification is equivalent to + noexcept(e). ### `execution::transform_sender` [exec.snd.transform] ### {#spec-execution.sender_transform}
 template<class Domain, sender Sndr, queryable... Env>
     requires (sizeof...(Env) <= 1)
-  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below);
+  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env)
+    noexcept(see below);
 
1. Let transformed-sndr be the expression @@ -5442,7 +6287,8 @@ template<class Domain, sender Sndr, queryable Env>
 template<class Domain, class Tag, sender Sndr, class... Args>
-  constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+  constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args)
+    noexcept(see below);
 
1. Let e be the expression `dom.apply_sender(Tag(), @@ -5460,9 +6306,9 @@ template<class Domain, class Tag, sender Sndr, class... Args> ### `execution::get_completion_signatures` [exec.getcomplsigs] ### {#spec-execution.getcomplsigs} 1. `get_completion_signatures` is a customization point object. Let `sndr` be an - expression such that `decltype((sndr))` is `Sndr`, and let `env` be an expression - such that `decltype((env))` is `Env`. Then `get_completion_signatures(sndr, env)` is - expression-equivalent to: + expression such that `decltype((sndr))` is `Sndr`, and let `env` be an + expression such that `decltype((env))` is `Env`. Then + `get_completion_signatures(sndr, env)` is expression-equivalent to: 1. `decltype(sndr.get_completion_signatures(env)){}` if that expression is well-formed, @@ -5474,7 +6320,8 @@ template<class Domain, class Tag, sender Sndr, class... Args>
             completion_signatures<
-              SET-VALUE-SIG(await-result-type<Sndr, env-promise<Env>>), // see [exec.snd.concepts]
+              SET-VALUE-SIG(await-result-type<Sndr,
+                            env-promise<Env>>), // see [exec.snd.concepts]
               set_error_t(exception_ptr),
               set_stopped_t()>{}
             
@@ -5496,13 +6343,15 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. `connect` connects ([async.ops]) a sender with a receiver. 2. The name `connect` denotes a customization point object. For subexpressions - `sndr` and `rcvr`, let `Sndr` be `decltype((sndr))` and `Rcvr` be `decltype((rcvr))`, and let - `DS` and `DR` be the decayed types of `Sndr` and `Rcvr`, respectively. + `sndr` and `rcvr`, let `Sndr` be `decltype((sndr))` and `Rcvr` be + `decltype((rcvr))`, and let `DS` and `DR` be the decayed types of `Sndr` and + `Rcvr`, respectively. 3. Let connect-awaitable-promise be the following class:
-    struct connect-awaitable-promise : with-await-transform<connect-awaitable-promise> {
+    struct connect-awaitable-promise
+      : with-await-transform<connect-awaitable-promise> {
       DR& rcvr; // exposition only
 
       connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
@@ -5735,43 +6584,65 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     sndr | c
     
- Given an additional pipeable sender adaptor closure object `d`, the expression `c | d` produces another pipeable sender adaptor closure object `e`: + Given an additional pipeable sender adaptor closure object `d`, the + expression `c | d` produces another pipeable sender adaptor closure object + `e`: - `e` is a perfect forwarding call wrapper ([func.require]) with the following properties: + `e` is a perfect forwarding call wrapper ([func.require]) with the following + properties: - - Its target object is an object `d2` of type `decay_t` direct-non-list-initialized with `d`. + - Its target object is an object `d2` of type `decay_t` + direct-non-list-initialized with `d`. - - It has one bound argument entity, an object `c2` of type `decay_t` direct-non-list-initialized with `C`. + - It has one bound argument entity, an object `c2` of type + `decay_t` direct-non-list-initialized with `C`. - - Its call pattern is `d2(c2(arg))`, where `arg` is the argument used in a function call expression of `e`. + - Its call pattern is `d2(c2(arg))`, where `arg` is the argument used in a + function call expression of `e`. - The expression `c | d` is well-formed if and only if the initializations of the state entities of `e` are all well-formed. + The expression `c | d` is well-formed if and only if the initializations of + the state entities of `e` are all well-formed. -2. An object `t` of type `T` is a pipeable sender adaptor closure object if `T` models `derived_from>`, `T` has no other base - classes of type `sender_adaptor_closure` for any other type `U`, and `T` does not model `sender`. +2. An object `t` of type `T` is a pipeable sender adaptor closure object if `T` + models `derived_from>`, `T` has no other base + classes of type `sender_adaptor_closure` for any other type `U`, and `T` + does not model `sender`. -3. The template parameter `D` for `sender_adaptor_closure` can be an incomplete type. Before any expression of type cv D appears as - an operand to the `|` operator, `D` shall be complete and model `derived_from>`. The behavior of an expression involving an - object of type cv D as an operand to the `|` operator is undefined if overload resolution selects a program-defined `operator|` - function. +3. The template parameter `D` for `sender_adaptor_closure` can be an incomplete + type. Before any expression of type cv D appears as an + operand to the `|` operator, `D` shall be complete and model + `derived_from>`. The behavior of an expression + involving an object of type cv D as an operand to the + `|` operator is undefined if overload resolution selects a program-defined + `operator|` function. -4. A pipeable sender adaptor object is a customization point object that accepts a `sender` as its first argument and returns a `sender`. +4. A pipeable sender adaptor object is a customization point object that + accepts a `sender` as its first argument and returns a `sender`. -5. If a pipeable sender adaptor object accepts only one argument, then it is a pipeable sender adaptor closure object. +5. If a pipeable sender adaptor object accepts only one argument, then it is a + pipeable sender adaptor closure object. -6. If a pipeable sender adaptor object `adaptor` accepts more than one argument, then let `sndr` be an expression such that `decltype((sndr))` models `sender`, - let `args...` be arguments such that `adaptor(sndr, args...)` is a well-formed expression as specified in the rest of this subclause - ([exec.adapt.objects]), and let `BoundArgs` be a pack that denotes `decay_t...`. The expression `adaptor(args...)` - produces a pipeable sender adaptor closure object `f` that is a perfect forwarding call wrapper with the following properties: +6. If a pipeable sender adaptor object `adaptor` accepts more than one argument, + then let `sndr` be an expression such that `decltype((sndr))` models + `sender`, let `args...` be arguments such that `adaptor(sndr, args...)` is a + well-formed expression as specified in the rest of this subclause + ([exec.adapt.objects]), and let `BoundArgs` be a pack that denotes + `decay_t...`. The expression `adaptor(args...)` produces a + pipeable sender adaptor closure object `f` that is a perfect forwarding call + wrapper with the following properties: - Its target object is a copy of `adaptor`. - - Its bound argument entities `bound_args` consist of objects of types `BoundArgs...` direct-non-list-initialized with `std::forward(args)...`, respectively. + - Its bound argument entities `bound_args` consist of objects of types + `BoundArgs...` direct-non-list-initialized with + `std::forward(args)...`, respectively. - - Its call pattern is `adaptor(rcvr, bound_args...)`, where `rcvr` is the argument used in a function call expression of `f`. + - Its call pattern is `adaptor(rcvr, bound_args...)`, where `rcvr` is the + argument used in a function call expression of `f`. - The expression `adaptor(args...)` is well-formed if and only if the initializations of the bound argument entities of the result, as specified above, - are all well-formed. + The expression `adaptor(args...)` is well-formed if and only if the + initializations of the bound argument entities of the result, as specified + above, are all well-formed. #### `execution::on` [exec.on] #### {#spec-execution.senders.adapt.on} @@ -7538,10 +8409,13 @@ template<class Domain, class Tag, sender Sndr, class... Args> concept always-true = true; // exposition only
- 1. A type `Fn` satisfies completion-signature if and only if it is a function type with one of the following forms: + 1. A type `Fn` satisfies completion-signature if and + only if it is a function type with one of the following forms: - * set_value_t(Vs...), where Vs is an arbitrary parameter pack. - * set_error_t(Err), where Err is an arbitrary type. + * set_value_t(Vs...), where Vs + is an arbitrary parameter pack. + * set_error_t(Err), where Err is + an arbitrary type. * `set_stopped_t()`
@@ -7553,29 +8427,30 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     
2. Let `Fns...` be a template parameter pack of the arguments of the - `completion_signatures` specialization named by - `Completions`, let TagFns be a - template parameter pack of the function types in `Fns` whose return types - are `Tag`, and let - Tsn be a template parameter - pack of the function argument types in the n-th type - in TagFns. Then, given two variadic templates + `completion_signatures` specialization named by `Completions`, let + TagFns be a template parameter pack of the function + types in `Fns` whose return types are `Tag`, and let + Tsn be a template parameter pack + of the function argument types in the n-th type in + TagFns. Then, given two variadic templates Tuple and Variant, the type - gather-signatures<Tag, Completions, Tuple, Variant> - names the type - META-APPLY(Variant, META-APPLY(Tuple, Ts0...), - META-APPLY(Tuple, Ts1...), ... - META-APPLY(Tuple, Tsm-1...)), where - m is the size of the parameter pack - TagFns and META-APPLY(T, As...) is - equivalent to: + gather-signatures<Tag, Completions, Tuple, + Variant> names the type + META-APPLY(Variant, META-APPLY(Tuple, + Ts0...), META-APPLY(Tuple, + Ts1...), ... META-APPLY(Tuple, + Tsm-1...)), where m + is the size of the parameter pack TagFns and + META-APPLY(T, As...) is equivalent to:
         typename indirect-meta-apply<always-true<As...>>::template meta-apply<T, As...>;
         
- 3. The purpose of META-APPLY is to make it - valid to use non-variadic templates as Variant and Tuple arguments to gather-signatures. + 3. The purpose of META-APPLY is + to make it valid to use non-variadic templates as + Variant and Tuple arguments to + gather-signatures. 4.
     template<completion-signature... Fns>
@@ -7655,53 +8530,70 @@ template<class Domain, class Tag, sender Sndr, class... Args>
       completion_signatures<see below>;
     
- * `SetValue` shall name an alias template such that for any template + 1. `SetValue` shall name an alias template such that for any template parameter pack `As...`, the type `SetValue` is either ill-formed - or else valid-completion-signatures<SetValue<As...>> + or else + valid-completion-signatures<SetValue<As...>> is satisfied. - * `SetError` shall name an alias template such that for any type `Err`, + 2. `SetError` shall name an alias template such that for any type `Err`, `SetError` is either ill-formed or else - valid-completion-signatures<SetError<Err>> - is satisfied. + valid-completion-signatures<SetError<Err>> is + satisfied. Then: - * Let `Vs...` be a pack of the types in the type-list named - by gather-signatures<set_value_t, InputSignatures, SetValue, type-list>. + 3. Let `Vs...` be a pack of the types in the type-list + named by gather-signatures<set_value_t, InputSignatures, + SetValue, type-list>. - * Let `Es...` be a pack of the types in the - type-list named by gather-signatures<set_error_t, InputSignatures, - type_identity_t, error-list>, where error-list is an - alias template such that error-list<Ts...> names - type-list<SetError<Ts>...>. + 4. Let `Es...` be a pack of the types in the type-list + named by gather-signatures<set_error_t, InputSignatures, + type_identity_t, error-list>, where + error-list is an alias template such that + error-list<Ts...> names + type-list<SetError<Ts>...>. - * Let `Ss` name the type `completion_signatures<>` if gather-signatures<set_stopped_t, InputSignatures, - type-list, type-list> is an alias for the type type-list<>; otherwise, `SetStopped`. + 5. Let `Ss` name the type `completion_signatures<>` if + gather-signatures<set_stopped_t, InputSignatures, + type-list, type-list> is an alias for the type + type-list<>; otherwise, `SetStopped`. - Then: + Then: - 1. If any of the above types are ill-formed, then - `transform_completion_signatures` is ill-formed, + 6. If any of the above types are ill-formed, then + `transform_completion_signatures` is ill-formed, - 2. Otherwise, `transform_completion_signatures` names the type `completion_signatures` - where `Sigs...` is the unique set of types in all the template arguments - of all the `completion_signatures` specializations in `[AdditionalSignatures, Vs..., Es..., Ss]`. + 7. Otherwise, `transform_completion_signatures` names the type + `completion_signatures` where `Sigs...` is the unique set of + types in all the template arguments of all the `completion_signatures` + specializations in `[AdditionalSignatures, Vs..., Es..., Ss]`. ## Execution contexts [exec.ctx] ## {#spec-execution.contexts} -1. This subclause specifies some execution resources on which work can be scheduled. +1. This subclause specifies some execution resources on which work can be + scheduled. ### `run_loop` [exec.run.loop] ### {#spec-execution.contexts.run_loop} -1. A `run_loop` is an execution resource on which work can be scheduled. It maintains a simple, thread-safe first-in-first-out queue of work. Its `run()` member function removes elements from the queue and executes them in a loop on whatever thread of execution calls `run()`. +1. A `run_loop` is an execution resource on which work can be scheduled. It + maintains a simple, thread-safe first-in-first-out queue of work. Its `run()` + member function removes elements from the queue and executes them in a loop + on whatever thread of execution calls `run()`. -2. A `run_loop` instance has an associated count that corresponds to the number of work items that are in its queue. Additionally, a `run_loop` has an associated state that can be one of starting, running, or finishing. +2. A `run_loop` instance has an associated count that corresponds to the + number of work items that are in its queue. Additionally, a `run_loop` has an + associated state that can be one of starting, running, + or finishing. -3. Concurrent invocations of the member functions of `run_loop`, other than `run` and its destructor, do not introduce data races. The member functions `pop_front`, `push_back`, and `finish` execute atomically. +3. Concurrent invocations of the member functions of `run_loop`, other than + `run` and its destructor, do not introduce data races. The member functions + `pop_front`, `push_back`, and `finish` execute atomically. -4. [Note: Implementations are encouraged to use an intrusive queue of operation states to hold the work units to make scheduling allocation-free. — end note] +4. Implementations are encouraged to use an intrusive + queue of operation states to hold the work units to make scheduling + allocation-free.
     class run_loop {
@@ -7735,52 +8627,78 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
 #### Associated types [exec.run.loop.types] #### {#spec-execution.contexts.run_loop.types}
 
-    
-    class run-loop-scheduler;
-    
- - 1. run-loop-scheduler is an unspecified type that models the `scheduler` concept. - - 2. Instances of run-loop-scheduler remain valid until the end of the lifetime of the `run_loop` instance from which they were obtained. - - 3. Two instances of run-loop-scheduler compare equal if and only if they were obtained from the same `run_loop` instance. - - 4. Let sch be an expression of type run-loop-scheduler. The expression schedule(sch) is not potentially-throwing and has type run-loop-sender. +
+class run-loop-scheduler;
+
-
-  class run-loop-sender;
-  
+1. run-loop-scheduler is an unspecified type that models + the `scheduler` concept. - 1. run-loop-sender is an unspecified type such that - sender-of<run-loop-sender> is `true`. - Additionally, the types reported by its `error_types` associated type is - `exception_ptr`, and the value of its `sends_stopped` trait is `true`. +2. Instances of run-loop-scheduler remain valid until the + end of the lifetime of the `run_loop` instance from which they were + obtained. - 2. An instance of run-loop-sender remains valid until the - end of the lifetime of its associated `run_loop` instance. +3. Two instances of run-loop-scheduler compare equal if + and only if they were obtained from the same `run_loop` instance. - 3. Let sndr be an expression of type - run-loop-sender, let rcvr be an - expression such that decltype(rcvr) models the - `receiver_of` concept, and let `C` be either `set_value_t` or - `set_stopped_t`. Then: +4. Let sch be an expression of type + run-loop-scheduler. The expression + schedule(sch) is not potentially-throwing and has type + run-loop-sender. - * The expression connect(sndr, rcvr) has type run-loop-opstate<decay_t<decltype(rcvr)>> and is potentially-throwing if and only if the initialiation of decay_t<decltype(rcvr)> from rcvr is potentially-throwing. +
+class run-loop-sender;
+
- * The expression get_completion_scheduler<C>(get_env(sndr)) is not potentially-throwing, has type run-loop-scheduler, and compares equal to the run-loop-scheduler instance from which sndr was obtained. +1. run-loop-sender is an unspecified type such that + sender-of<run-loop-sender> is `true`. + Additionally, the types reported by its `error_types` associated type is + `exception_ptr`, and the value of its `sends_stopped` trait is `true`. + +2. An instance of run-loop-sender remains valid until the + end of the lifetime of its associated `run_loop` instance. + +3. Let sndr be an expression of type + run-loop-sender, let rcvr be an + expression such that decltype(rcvr) models the + `receiver_of` concept, and let `C` be either `set_value_t` or + `set_stopped_t`. Then: + + * The expression connect(sndr, rcvr) has type + run-loop-opstate<decay_t<decltype(rcvr)>> + and is potentially-throwing if and only if the initialiation of + decay_t<decltype(rcvr)> from + rcvr is potentially-throwing. + + * The expression + get_completion_scheduler<C>(get_env(sndr)) is + not potentially-throwing, has type + run-loop-scheduler, and compares equal to the + run-loop-scheduler instance from which + sndr was obtained. -
-  template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
-    struct run-loop-opstate;
-  
+
+template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
+  struct run-loop-opstate;
+
- 1. run-loop-opstate<Rcvr> inherits unambiguously from run-loop-opstate-base. +1. run-loop-opstate<Rcvr> inherits unambiguously + from run-loop-opstate-base. - 2. Let o be a non-`const` lvalue of type run-loop-opstate<Rcvr>, and let REC(o) be a non-`const` lvalue reference to an instance of type Rcvr that was initialized with the expression rcvr passed to the invocation of `connect` that returned o. Then: +2. Let o be a non-`const` lvalue of type + run-loop-opstate<Rcvr>, and let + REC(o) be a non-`const` lvalue reference to an + instance of type Rcvr that was initialized with the + expression rcvr passed to the invocation of `connect` + that returned o. Then: - * The object to which REC(o) refers remains valid for the lifetime of the object to which o refers. + * The object to which REC(o) refers remains + valid for the lifetime of the object to which o + refers. - * The type run-loop-opstate<Rcvr> overrides run-loop-opstate-base::execute() such that o.execute() is equivalent to the following: + * The type run-loop-opstate<Rcvr> overrides + run-loop-opstate-base::execute() such that + o.execute() is equivalent to the following:
         if (get_stop_token(REC(o)).stop_requested()) {
@@ -7790,7 +8708,8 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         }
         
- * The expression start(o) is equivalent to the following: + * The expression start(o) is equivalent to the + following:
         try {
@@ -7802,75 +8721,88 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
 #### Constructor and destructor [exec.run.loop.ctor] #### {#spec-execution.contexts.run_loop.ctor}
 
-    
-    run_loop::run_loop() noexcept;
-    
+
+run_loop::run_loop() noexcept;
+
- 1. Postconditions: count is `0` and state is starting. +1. Postconditions: count is `0` and state is + starting. -
-    run_loop::~run_loop();
-    
+
+run_loop::~run_loop();
+
- 1. Effects: If count is not `0` or if state is running, invokes `terminate()`. Otherwise, has no effects. +1. Effects: If count is not `0` or if state is + running, invokes `terminate()`. Otherwise, has no effects. #### Member functions [exec.run.loop.members] #### {#spec-execution.contexts.run_loop.members} -
-    run-loop-opstate-base* run_loop::pop_front();
-    
+
+run-loop-opstate-base* run_loop::pop_front();
+
- 1. Effects: Blocks ([defns.block]) until one of the following conditions is `true`: +1. Effects: Blocks ([defns.block]) until one of the following conditions + is `true`: - * count is `0` and state is finishing, in which case `pop_front` returns `nullptr`; or + * count is `0` and state is finishing, in which case + `pop_front` returns `nullptr`; or - * count is greater than `0`, in which case an item is removed from the front of the queue, count is decremented by `1`, and the removed item is returned. + * count is greater than `0`, in which case an item is removed from + the front of the queue, count is decremented by `1`, and the + removed item is returned. -
-    void run_loop::push_back(run-loop-opstate-base* item);
-    
+
+void run_loop::push_back(run-loop-opstate-base* item);
+
- 1. Effects: Adds `item` to the back of the queue and increments count by `1`. +1. Effects: Adds `item` to the back of the queue and increments + count by `1`. - 2. Synchronization: This operation synchronizes with the `pop_front` operation that obtains `item`. +2. Synchronization: This operation synchronizes with the `pop_front` + operation that obtains `item`. -
-    run-loop-scheduler run_loop::get_scheduler();
-    
+
+run-loop-scheduler run_loop::get_scheduler();
+
- 1. Returns: an instance of run-loop-scheduler that can be used to schedule work onto this `run_loop` instance. +1. Returns: an instance of run-loop-scheduler that + can be used to schedule work onto this `run_loop` instance. -
-    void run_loop::run();
-    
+
+void run_loop::run();
+
- 1. Effects: Equivalent to: +1. Effects: Equivalent to: -
-        while (auto* op = pop_front()) {
-          op->execute();
-        }
-        
+
+    while (auto* op = pop_front()) {
+      op->execute();
+    }
+    
- 2. Precondition: state is starting. +2. Precondition: state is starting. - 3. Postcondition: state is finishing. +3. Postcondition: state is finishing. - 4. Remarks: While the loop is executing, state is running. When state changes, it does so without introducing data races. +4. Remarks: While the loop is executing, state is running. + When state changes, it does so without introducing data races. -
-    void run_loop::finish();
-    
+
+void run_loop::finish();
+
- 1. Effects: Changes state to finishing. +1. Effects: Changes state to finishing. - 2. Synchronization: This operation synchronizes with all `pop_front` operations on this object. +2. Synchronization: This operation synchronizes with all `pop_front` + operations on this object. ## Coroutine utilities [exec.coro.utils] ## {#spec-execution.coro_utils} ### `execution::as_awaitable` [exec.as.awaitable] ### {#spec-execution.coro_utils.as_awaitable} -1. `as_awaitable` transforms an object into one that is awaitable within a particular coroutine. This subclause makes use of the following exposition-only entities: +1. `as_awaitable` transforms an object into one that is awaitable within a + particular coroutine. This subclause makes use of the following + exposition-only entities:
     template<class Sndr, class Env>
@@ -7895,15 +8827,26 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     1. Alias template single-sender-value-type is defined as follows:
 
-        1. If `value_types_of_t` would have the form `Variant>`, then single-sender-value-type<Sndr, Env> is an alias for type `decay_t`.
+        1. If `value_types_of_t` would have the form
+            `Variant>`, then
+            single-sender-value-type<Sndr, Env> is an
+            alias for type `decay_t`.
 
-        2. Otherwise, if `value_types_of_t` would have the form `Variant>` or `Variant<>`, then single-sender-value-type<Sndr, Env> is an alias for type `void`.
+        2. Otherwise, if `value_types_of_t` would
+            have the form `Variant>` or `Variant<>`, then
+            single-sender-value-type<Sndr, Env> is an
+            alias for type `void`.
 
-        3. Otherwise, if `value_types_of_t` would have the form `Variant>` where `Ts` is a parameter pack, then single-sender-value-type<Sndr, Env> is an alias for type `std::tuple...>`.
+        3. Otherwise, if `value_types_of_t` would
+            have the form `Variant>` where `Ts` is a parameter pack,
+            then single-sender-value-type<Sndr, Env> is an
+            alias for type `std::tuple...>`.
 
-        4. Otherwise, single-sender-value-type<Sndr, Env> is ill-formed.
+        4. Otherwise, single-sender-value-type<Sndr, Env>
+            is ill-formed.
 
-    2. The type sender-awaitable<Sndr, Promise> is equivalent to the following:
+    2. The type sender-awaitable<Sndr, Promise> is
+        equivalent to the following:
 
         
         template<class Sndr, class Promise>
@@ -7935,39 +8878,50 @@ template<class Domain, class Tag, sender Sndr, class... Args>
             };
             
- Let `rcvr` be an rvalue expression of type awaitable-receiver, let `crcvr` be a `const` lvalue that refers to `rcvr`, let `vs` be a parameter pack of types `Vs...`, and let `err` be an arbitrary expression of type `Err`. Then: + Let `rcvr` be an rvalue expression of type + awaitable-receiver, let `crcvr` be a `const` + lvalue that refers to `rcvr`, let `vs` be a parameter pack of types + `Vs...`, and let `err` be an arbitrary expression of type `Err`. + Then: - 1. If `constructible_from` is satisfied, the expression `set_value(rcvr, vs...)` is equivalent to: + 1. If `constructible_from` is satisfied, the + expression `set_value(rcvr, vs...)` is equivalent to: -
-                  try {
-                    rcvr.result_ptr_->emplace<1>(vs...);
-                  } catch(...) {
-                    rcvr.result_ptr_->emplace<2>(current_exception());
-                  }
-                  rcvr.continuation_.resume();
-                  
+
+                try {
+                  rcvr.result_ptr_->emplace<1>(vs...);
+                } catch(...) {
+                  rcvr.result_ptr_->emplace<2>(current_exception());
+                }
+                rcvr.continuation_.resume();
+                
- Otherwise, `set_value(rcvr, vs...)` is ill-formed. + Otherwise, `set_value(rcvr, vs...)` is ill-formed. - 2. The expression `set_error(rcvr, err)` is equivalent to: + 2. The expression `set_error(rcvr, err)` is equivalent to: -
-                  rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
-                  rcvr.continuation_.resume();
-                  
+
+                rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
+                rcvr.continuation_.resume();
+                
- 3. The expression `set_stopped(rcvr)` is equivalent to + 3. The expression `set_stopped(rcvr)` is equivalent to static_cast<coroutine_handle<>>(rcvr.continuation_.promise().unhandled_stopped()).resume(). - 4. For any expression `tag` whose type satisfies forwarding-query - and for any pack of subexpressions `as`, `get_env(crcvr).query(tag, as...)` - is expression-equivalent to tag(get_env(as_const(crcvr.continuation_.promise())), - as...) when that expression is well-formed. + 4. For any expression `tag` whose type satisfies + forwarding-query and for any pack of + subexpressions `as`, `get_env(crcvr).query(tag, as...)` is + expression-equivalent to + tag(get_env(as_const(crcvr.continuation_.promise())), + as...) when that expression is well-formed. - 2. sender-awaitable::sender-awaitable(Sndr&& sndr, Promise& p) + 2. sender-awaitable::sender-awaitable(Sndr&& + sndr, Promise& p) - - Effects: initializes `state_` with connect(std::forward<Sndr>(sndr), awaitable-receiver{&result_, coroutine_handle<Promise>::from_promise(p)}). + - Effects: initializes `state_` with + connect(std::forward<Sndr>(sndr), + awaitable-receiver{&result_, + coroutine_handle<Promise>::from_promise(p)}). 3. value_t sender-awaitable::await_resume() @@ -7990,26 +8944,33 @@ template<class Domain, class Tag, sender Sndr, class... Args> * Mandates: is-awaitable<A, Promise> is `true`, where `A` is the type of the expression above. - 2. Otherwise, `expr` if is-awaitable<Expr, U> is - `true`, where U is an unspecified class type that + 2. Otherwise, `expr` if is-awaitable<Expr, U> + is `true`, where U is an unspecified class type that lacks a member named `await_transform`. The - condition is not is-awaitable<Expr, Promise> as that - creates the potential for constraint recursion. + condition is not is-awaitable<Expr, Promise> as + that creates the potential for constraint recursion. - * Preconditions: is-awaitable<Expr, Promise> is - `true` and the expression `co_await expr` in a coroutine with promise - type U is expression-equivalent to the same - expression in a coroutine with promise type `Promise`. + * Preconditions: is-awaitable<Expr, + Promise> is `true` and the expression `co_await expr` in a + coroutine with promise type U is + expression-equivalent to the same expression in a coroutine with + promise type `Promise`. - 3. Otherwise, sender-awaitable{expr, p} if awaitable-sender<Expr, Promise> is `true`. + 3. Otherwise, sender-awaitable{expr, p} if + awaitable-sender<Expr, Promise> is `true`. 4. Otherwise, `expr`. ### `execution::with_awaitable_senders` [exec.with.awaitable.senders] ### {#spec-execution.coro_utils.with_awaitable_senders} - 1. `with_awaitable_senders`, when used as the base class of a coroutine promise type, makes senders awaitable in that coroutine type. +1. `with_awaitable_senders`, when used as the base class of a coroutine promise + type, makes senders awaitable in that coroutine type. - In addition, it provides a default implementation of `unhandled_stopped()` such that if a sender completes by calling `set_stopped`, it is treated as if an uncatchable "stopped" exception were thrown from the await-expression. In practice, the coroutine is never resumed, and the `unhandled_stopped` of the coroutine caller's promise type is called. + In addition, it provides a default implementation of `unhandled_stopped()` + such that if a sender completes by calling `set_stopped`, it is treated as + if an uncatchable "stopped" exception were thrown from the + await-expression. In practice, the coroutine is never resumed, and + the `unhandled_stopped` of the coroutine caller's promise type is called.
     template<class-type Promise>
@@ -8027,7 +8988,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         template<class Value>
         see below await_transform(Value&& value);
 
-       private:
+        private:
         // exposition only
         [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
           terminate();
@@ -8038,29 +8999,29 @@ template<class Domain, class Tag, sender Sndr, class... Args>
       };
     
- 2. `void set_continuation(coroutine_handle h) noexcept` +2. `void set_continuation(coroutine_handle h) noexcept` - - Effects: equivalent to: + - Effects: equivalent to: -
-        continuation_ = h;
-        if constexpr ( requires(OtherPromise& other) { other.unhandled_stopped(); } ) {
-          stopped_handler_ = [](void* p) noexcept -> coroutine_handle<> {
-            return coroutine_handle<OtherPromise>::from_address(p)
-              .promise().unhandled_stopped();
-          };
-        } else {
-          stopped_handler_ = default_unhandled_stopped;
-        }
-        
+
+      continuation_ = h;
+      if constexpr ( requires(OtherPromise& other) { other.unhandled_stopped(); } ) {
+        stopped_handler_ = [](void* p) noexcept -> coroutine_handle<> {
+          return coroutine_handle<OtherPromise>::from_address(p)
+            .promise().unhandled_stopped();
+        };
+      } else {
+        stopped_handler_ = default_unhandled_stopped;
+      }
+      
- 3. call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value) +3. call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value) - - Effects: equivalent to: + - Effects: equivalent to: -
-        return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));
-        
+
+      return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));
+      
 {

From 49f783519451e67023b0f6f501cfe08b22123e82 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Wed, 20 Mar 2024 12:28:23 -0700
Subject: [PATCH 39/89] a few more tweaks

---
 execution.bs | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)

diff --git a/execution.bs b/execution.bs
index 61d51ba..1c1c07a 100644
--- a/execution.bs
+++ b/execution.bs
@@ -3793,20 +3793,19 @@ std::tuple>`.
 ## Customization points ## {#design-dispatch}
 
 Earlier versions of this paper used a dispatching technique known as
-[`tag_invoke`](https://wg21.link/P1895) to allow for customization of basis
-operations and sender algorithms. This technique used private friend functions
-named "`tag_invoke`" that are found by argument-dependent look-up. The
-`tag_invoke` overloads are distinguished from each other by their first
-argument, which is the type of the customization point object being customized.
-For instance, to customize the `execution::set_value` operation, a receiver type
-might do the following:
+`tag_invoke` (see [[P1895R0]]) to allow for customization of basis operations
+and sender algorithms. This technique used private friend functions named
+"`tag_invoke`" that are found by argument-dependent look-up. The `tag_invoke`
+overloads are distinguished from each other by their first argument, which is
+the type of the customization point object being customized. For instance, to
+customize the `execution::set_value` operation, a receiver type might do the
+following:
 
 
 struct my_receiver {
   friend void tag_invoke(execution::set_value_t, my_receiver&& self, int value) noexcept {
     std::cout << "received value: " << value;
   }
-
   //...
 };
 
@@ -3826,7 +3825,6 @@ struct my_receiver { void set_value(int value) && noexcept { std::cout << "received value: " << value; } - //... };
@@ -3874,8 +3872,7 @@ more information. Much of this wording follows the wording of [[P0443R14]]. [[#spec-utilities]] is meant to be a diff relative to the wording of the -[utilities] clause of [[N4885]]. This diff applies changes from -[[P1895R0]]. +[utilities] clause of [[N4885]]. [[#spec-thread]] is meant to be a diff relative to the wording of the [thread] clause of [[N4885]]. This diff applies changes from [[P2175R0]]. From d79d8daeeb825ac236b79b6bc81aeac4757f12b4 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 20 Mar 2024 12:32:00 -0700 Subject: [PATCH 40/89] fix a few bugs --- execution.bs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/execution.bs b/execution.bs index 1c1c07a..cb1700d 100644 --- a/execution.bs +++ b/execution.bs @@ -481,7 +481,7 @@ struct recv_op : operation_base { // May be completing concurrently on another thread already. if (stopPossible) { // Register the stop callback - stopCallback.emplace(std::move(st), cancel_cb{self}); + stopCallback.emplace(std::move(st), cancel_cb{*this}); // Mark as 'completed' if (ready.load(std::memory_order_acquire) || @@ -489,7 +489,7 @@ struct recv_op : operation_base { // Already completed on another thread stopCallback.reset(); - BOOL ok = WSAGetOverlappedResult(sock, (WSAOVERLAPPED*)&self, &bytesTransferred, FALSE, &flags); + BOOL ok = WSAGetOverlappedResult(sock, (WSAOVERLAPPED*)this, &bytesTransferred, FALSE, &flags); if (ok) { std::execution::set_value(std::move(receiver), bytesTransferred); } else { @@ -695,7 +695,7 @@ struct _then_sender { } decltype(auto) get_env() const noexcept { - return get_env(self.s_); + return get_env(s_); } }; From 77cf6eadea0de721b42f1903f2912e8ee875e2a6 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 20 Mar 2024 12:41:41 -0700 Subject: [PATCH 41/89] add explicit opt-in for operation_state concept --- execution.bs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/execution.bs b/execution.bs index cb1700d..678c098 100644 --- a/execution.bs +++ b/execution.bs @@ -427,6 +427,8 @@ struct operation_base : WSAOVERALAPPED { template struct recv_op : operation_base { + using operation_state_concept = std::execution::operation_state_t; + recv_op(SOCKET s, void* data, size_t len, Receiver r) : receiver(std::move(r)) , sock(s) { @@ -772,6 +774,7 @@ struct _retry_receiver // re-construct and re-start it if the operation fails. template struct _retry_op { + using operation_state_concept = stdexec::operation_state_t; using _child_op_t = stdexec::connect_result_t>; @@ -899,7 +902,9 @@ namespace stdexec = std::execution; class inline_scheduler { template struct _op { + using operation_state_concept = operation_state_t; R rec_; + void start() & noexcept { stdexec::set_value(std::move(rec_)); } @@ -4871,6 +4876,8 @@ namespace std::execution { inline constexpr set_stopped_t set_stopped{}; // [exec.opstate], operation states + struct operation_state_t {}; + template<class O> concept operation_state = see below; @@ -5456,8 +5463,15 @@ enum class forward_progress_guarantee { type ([async.ops]).
+    template<class Rcvr>
+      concept enable-opstate = // exposition only
+        requires {
+          requires derived_from<typename Rcvr::operation_state_concept, operation_state_t>;
+        };
+
     template<class O>
       concept operation_state =
+        enable-opstate<remove_cvref_t<O>> &&
         queryable<O> &&
         is_object_v<O> &&
         requires (O& o) {
@@ -5815,6 +5829,7 @@ enum class forward_progress_guarantee {
                 requires well-formed<state-type, Sndr, Rcvr> &&
                   well-formed<inner-ops-tuple, Sndr, Rcvr>
               struct basic-operation {  // exposition only
+                using operation_state_concept = operation_state_t;
                 using tag-type = tag_of_t<Sndr>; // exposition only
 
                 Rcvr rcvr_; // exposition only
@@ -6378,6 +6393,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     
     struct operation-state-task {
+      using operation_state_concept = operation_state_t;
       using promise_type = connect-awaitable-promise;
       coroutine_handle<> coro; // exposition only
 

From 87adc76a23abd357eb05bfa5fdb73b0caf6aa561 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Wed, 20 Mar 2024 14:40:29 -0700
Subject: [PATCH 42/89] remove class qualification in receiver_adaptor spec

---
 execution.bs | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/execution.bs b/execution.bs
index 678c098..ea3f09f 100644
--- a/execution.bs
+++ b/execution.bs
@@ -8319,7 +8319,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     
     template<class... Args>
-      void receiver_adaptor<Derived, Base>::set_value(Args&&... args) && noexcept;
+      void set_value(Args&&... args) && noexcept;
     
1. Let `e` be the expression @@ -8331,7 +8331,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template<class Error>
-      void receiver_adaptor<Derived, Base>::set_error(Error&& err) && noexcept;
+      void set_error(Error&& err) && noexcept;
     
1. Let `e` be the expression @@ -8342,7 +8342,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 3. Effects: Equivalent to `e`.
-    void receiver_adaptor<Derived, Base>::set_stopped() && noexcept;
+    void set_stopped() && noexcept;
     
1. Let `e` be the expression @@ -8354,7 +8354,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template<class Self>
-      decltype(auto) receiver_adaptor<Derived, Base>::get-base(this Self&& self) noexcept;
+      decltype(auto) get-base(this Self&& self) noexcept;
     
1. Let `e` be the expression @@ -8370,7 +8370,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template<class Self>
-      decltype(auto) receiver_adaptor<Derived, Base>::base(this Self&& self) noexcept requires HAS-BASE;
+      decltype(auto) base(this Self&& self) noexcept requires HAS-BASE;
     
1. Let `e` be the expression From db01d39ac0750c6d006b013256f5fdf81015eb9b Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 21 Mar 2024 13:42:07 -0700 Subject: [PATCH 43/89] remove `receiver_adaptor` --- execution.bs | 244 +++++++++++++-------------------------------------- 1 file changed, 61 insertions(+), 183 deletions(-) diff --git a/execution.bs b/execution.bs index ea3f09f..21ad5ff 100644 --- a/execution.bs +++ b/execution.bs @@ -648,18 +648,16 @@ implementations. ```c++ namespace stdexec = std::execution; -template -class _then_receiver - : public stdexec::receiver_adaptor<_then_receiver, R> { +template +class _then_receiver : public R { F f_; public: - _then_receiver(R r, F f) - : stdexec::receiver_adaptor<_then_receiver, R>{std::move(r)} - , f_(std::move(f)) {} + _then_receiver(R r, F f) : R(std::move(r)), f_(std::move(f)) {} - // Customize set_value by invoking the callable and passing the result to the inner receiver - template + // Customize set_value by invoking the callable and passing the result to + // the inner receiver + template requires std::invocable void set_value(As&&... as) && noexcept { try { @@ -670,7 +668,7 @@ class _then_receiver } }; -template +template struct _then_sender { using sender_concept = stdexec::sender_t; S s_; @@ -680,20 +678,22 @@ struct _then_sender { using _set_value_t = stdexec::completion_signatures< stdexec::set_value_t(std::invoke_result_t)>; + using _except_ptr_sig = + stdexec::completion_signatures; + // Compute the completion signatures - template + template auto get_completion_signatures(Env&& env) && noexcept - -> stdexec::transform_completion_signatures_of, - _set_value_t> { + -> stdexec::transform_completion_signatures_of< + S, Env, _except_ptr_sig, _set_value_t> { return {}; } // Connect: - template + template auto connect(R r) && -> stdexec::connect_result_t> { - return stdexec::connect( - (S&&) s_, _then_receiver{(R&&) r, (F&&) f_}); + return stdexec::connect( + (S&&) s_, _then_receiver{(R&&) r, (F&&) f_}); } decltype(auto) get_env() const noexcept { @@ -701,7 +701,7 @@ struct _then_sender { } }; -template +template stdexec::sender auto then(S s, F f) { return _then_sender{(S&&) s, (F&&) f}; } @@ -714,15 +714,11 @@ well as all receiver queries, are passed through unchanged. In detail, it does the following: -1. Defines a receiver in terms of `execution::receiver_adaptor` that aggregates - another receiver and an invocable that: +1. Defines a receiver in terms of receiver and an invocable that: * Defines a constrained `set_value` member function for transforming the value channel. * Delegates `set_error` and `set_stopped` to the inner receiver. - The `set_error` and `set_stopped` member functions are provided by - `receiver_adaptor`. - 2. Defines a sender that aggregates another sender and the invocable, which defines a `connect` member function that wraps the incoming receiver in the receiver from (1) and passes it and the incoming sender to @@ -742,10 +738,12 @@ concept _decays_to = same_as, To>; // _conv needed so we can emplace construct non-movable types into // a std::optional. template - requires is_nothrow_move_constructible_v struct _conv { F f_; + + static_assert(is_nothrow_move_constructible_v); explicit _conv(F f) noexcept : f_((F&&) f) {} + operator invoke_result_t() && { return ((F&&) f_)(); } @@ -754,20 +752,27 @@ struct _conv { template struct _retry_op; -// pass through all customizations except set_error, which retries the operation. +// pass through all customizations except set_error, which retries +// the operation. template -struct _retry_receiver - : stdexec::receiver_adaptor<_retry_receiver> { +struct _retry_receiver { _retry_op* o_; - R&& base() && noexcept { return std::move(o_->r_); } - const R& base() const & noexcept { return o_->r_; } - - explicit _retry_receiver(_retry_op* o) : o_(o) {} + void set_value(auto&&... as) && noexcept { + stdexec::set_value(std::move(o_->r_), (decltype(as)&&) as...); + } void set_error(auto&&) && noexcept { o_->_retry(); // This causes the op to be retried } + + void set_stopped() && noexcept { + stdexec::set_stopped(std::move(o_->r_)); + } + + decltype(auto) get_env() const noexcept { + return get_env(o_->r_); + } }; // Hold the nested operation state in an optional so we can @@ -1213,8 +1218,6 @@ that the completion-signal of will be transferred to the given context. 10. Some additional utilities are added: * `run_loop`: An execution resource that provides a multi-producer, single-consumer, first-in-first-out work queue. - * `receiver_adaptor`: A utility for algorithm authors for defining one - receiver type in terms of another. * `completion_signatures` and `transform_completion_signatures`: Utilities for describing the ways in which a sender can complete in a declarative syntax. @@ -1461,8 +1464,11 @@ The changes since R8 are as follows: * The `tag_invoke` mechanism has been replace with member functions for customizations as per \[P2855](https://wg21.link/p2855). - * The removal of `tag_invoke` necessitated a respecification of the - `receiver_adaptor` utility. + * Per guidance from LWG and LEWG, `receiver_adaptor` has been removed. + + * The `receiver` concept is tweaked to requires that receiver types are not + `final`. Without `receiver_adaptor` and `tag_invoke`, receiver adaptors + are easily written using implementation inheritance. Enhancements: @@ -5023,10 +5029,6 @@ namespace std::execution { inline constexpr start_detached_t start_detached{}; // [exec.utils], sender and receiver utilities - // [exec.utils.rcvr.adptr] - template<class-type Derived, receiver Base = unspecified> - class receiver_adaptor; - // [exec.utils.cmplsigs] template<class Fn> concept completion-signature = // exposition only @@ -5425,6 +5427,8 @@ enum class forward_progress_guarantee { receiver<Rcvr> && has-completions<Rcvr, Completions>;
+2. Class types that are `final` do not model the `receiver` concept. + 3. Let `rcvr` be a receiver and let `op_state` be an operation state associated with an asynchronous operation created by connecting `rcvr` with a sender. Let `token` be a stop token equal to `get_stop_token(get_env(rcvr))`. `token` shall @@ -6848,7 +6852,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> 3. Let `receiver-type` denote the following class:
-                struct receiver-type : receiver_adaptor<receiver-type> {
+                struct receiver-type {
+                  using receiver_concept = receiver_t;
                   state-type* state; // exposition only
 
                   Rcvr&& base() && noexcept { return std::move(state->rcvr); }
@@ -6864,6 +6869,19 @@ template<class Domain, class Tag, sender Sndr, class... Args>
                       },
                       state->async-result);
                   }
+
+                  template<class Error>
+                  void set_error(Error&& err) && noexcept {
+                    execution::set_error(std::move(state->rcvr), std::forward<Error>(err));
+                  }
+
+                  void set_stopped() && noexcept {
+                    execution::set_stopped(std::move(state->rcvr));
+                  }
+
+                  decltype(auto) get_env() const noexcept {
+                    return FWD-ENV(execution::get_env(state->rcvr));
+                  }
                 };
                 
@@ -7010,12 +7028,13 @@ template<class Domain, class Tag, sender Sndr, class... Args>
             template<class Rcvr, class Env>
-            struct receiver2 : receiver_adaptor<receiver2<Rcvr, Env>, Rcvr> {
+            struct receiver2 : Rcvr {
               explicit receiver2(Rcvr rcvr, Env env)
-                : receiver2::receiver_adaptor{std::move(rcvr)}, env(std::move(env)) {}
+                : Rcvr(std::move(rcvr)), env(std::move(env)) {}
 
               auto get_env() const noexcept {
-                return JOIN-ENV(env, FWD-ENV(execution::get_env(this->base())));
+                const Rcvr& rcvr = *this;
+                return JOIN-ENV(env, FWD-ENV(execution::get_env(rcvr)));
               }
 
               Env env; // exposition only
@@ -8238,147 +8257,6 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
 ## Sender/receiver utilities [exec.utils] ## {#spec-execution.snd_rec_utils}
 
-### `execution::receiver_adaptor` [exec.utils.rcvr.adptr] ### {#spec-execution.snd_rec_utils.rcvr_adptr}
-
-    
-    template<class-type Derived, receiver Base = unspecified>
-      class receiver_adaptor;
-    
- -1. `receiver_adaptor` simplifies the implementation of one receiver type in - terms of another. It defines named member functions that forward to - identically named members in the derived type if they exist, and to the - adapted receiver otherwise. - -2. Let HAS-BASE be `false` if `Base` is an alias for the - unspecified default template argument; otherwise, it is `true`. - -3. `receiver_adaptor` is as follows: - -
-    template<class-type Derived, receiver Base = unspecified>
-    class receiver_adaptor {
-     public:
-      using receiver_concept = receiver_t;
-
-      // Constructors
-      receiver_adaptor() = default;
-      template<class B>
-          requires HAS-BASE && constructible_from<Base, B>
-        explicit receiver_adaptor(B&& b) : base-rcvr(std::forward<B>(b)) {}
-
-      // Member functions
-      template<class... Args>
-        void set_value(Args&&... args) && noexcept;
-
-      template<class Error>
-        void set_error(Error&& err) && noexcept;
-
-      void set_stopped() && noexcept;
-
-      decltype(auto) get_env() const noexcept {
-        return execution::get_env(get-base());
-      }
-
-     private:
-      friend Derived;
-
-      // Private member functions
-      template<class Self>
-        decltype(auto) get-base(this Self&& self) noexcept; // exposition only
-
-      template<class Self>
-        decltype(auto) base(this Self&& self) noexcept requires HAS-BASE;
-
-      Base base-rcvr; // exposition only, present if and only if HAS-BASE is true
-    };
-    
- -4. [Note: The `Derived` template parameter denotes a class type that is - incomplete when `receiver_adaptor` is instantiated.] - -5. [Example: -
-     using _int_completion =
-       completion_signatures<set_value_t(int)>;
-
-     template<receiver_of<_int_completion> Rcvr>
-       struct my_receiver
-         : receiver_adaptor<my_receiver<Rcvr>, Rcvr> {
-         explicit my_receiver(Rcvr r)
-           : receiver_adaptor<my_receiver, Rcvr>(std::move(r)) {}
-
-         void set_value() && noexcept {
-           std::execution::set_value(std::move(*this).base(), 42);
-         }
-       };
-     
- -- end example] - -#### Member functions [exec.utils.rcvr.adptr.members] #### {#spec-execution.snd_rec_utils.receiver_adaptor.members} - -
-    template<class... Args>
-      void set_value(Args&&... args) && noexcept;
-    
- - 1. Let `e` be the expression - execution::set_value(std::move(get-base()), std::forward<Args>(args)...). - - 2. Constraints: `e` is a well-formed expression. - - 3. Effects: Equivalent to `e`. - -
-    template<class Error>
-      void set_error(Error&& err) && noexcept;
-    
- - 1. Let `e` be the expression - execution::set_error(std::move(get-base()), std::forward<Error>(err)). - - 2. Constraints: `e` is a well-formed expression. - - 3. Effects: Equivalent to `e`. - -
-    void set_stopped() && noexcept;
-    
- - 1. Let `e` be the expression - execution::set_stopped(std::move(get-base())). - - 2. Constraints: `e` is a well-formed expression. - - 3. Effects: Equivalent to `e`. - -
-    template<class Self>
-      decltype(auto) get-base(this Self&& self) noexcept;
-    
- - 1. Let `e` be the expression - std::forward_like<Self>((Derived&) self).base() if that expression - is well-formed; otherwise, it is - std::forward_like<Self>((receiver_adaptor&) self).base(). - The C-style casts are to disable accessibility checks. - - 2. Mandates: `is_base_of_v` is `true` and `e` - is a well-formed expression. - - 3. Returns: `e`. - -
-    template<class Self>
-      decltype(auto) base(this Self&& self) noexcept requires HAS-BASE;
-    
- - 1. Let `e` be the expression - std::forward_like<Self>((receiver_adaptor&) self).base-rcvr. - The C-style cast is to disable accessibility checks. - - 3. Returns: (e). - ### `execution::completion_signatures` [exec.utils.cmplsigs] ### {#spec-execution.snd_rec_utils.completion_sigs} 1. `completion_signatures` is a type that encodes a set of completion signatures From 4b6d9d0c41a8db83ff7cd9cac4b31357ba3fb692 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 28 Mar 2024 12:10:29 -0700 Subject: [PATCH 44/89] [WIP] edits from the final tokyo lwg session --- execution.bs | 1385 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 1011 insertions(+), 374 deletions(-) diff --git a/execution.bs b/execution.bs index 21ad5ff..9c023f5 100644 --- a/execution.bs +++ b/execution.bs @@ -27,6 +27,9 @@ Default Highlight: c++
# Introduction # {#intro} -This paper proposes a self-contained design for a Standard C++ framework for managing asynchronous execution on generic execution resources. It is based on the ideas in [[P0443R14]] and its companion papers. +This paper proposes a self-contained design for a Standard C++ framework for +managing asynchronous execution on generic execution resources. It is based on +the ideas in [[P0443R14]] and its companion papers. ## Motivation ## {#motivation} @@ -425,7 +466,7 @@ struct operation_base : WSAOVERALAPPED { completion_fn* completed; }; -template +template struct recv_op : operation_base { using operation_state_concept = std::execution::operation_state_t; @@ -529,11 +570,12 @@ struct recv_op : operation_base { } } + using stop_callback_t = stop_callback_of_t>, cancel_cb>; + Receiver receiver; SOCKET sock; WSABUF buffer; - std::optional - ::template callback_type> stopCallback; + std::optional stopCallback; std::atomic ready{false}; }; @@ -543,7 +585,7 @@ struct recv_sender { void* data; size_t len; - template + template recv_op connect(Receiver r) const { return recv_op{sock, data, len, std::move(r)}; } @@ -2760,7 +2802,7 @@ function call syntax. ## A range of senders represents an async sequence of data ## {#design-range-of-senders} Senders represent a single unit of asynchronous work. In many cases though, what -is being modelled is a sequence of data arriving asynchronously, and you want +is being modeled is a sequence of data arriving asynchronously, and you want computation to happen on demand, when each element arrives. This requires nothing more than what is in this paper and the range support in C++20. A range of senders would allow you to model such input as keystrikes, mouse movements, @@ -3891,427 +3933,999 @@ Much of this wording follows the wording of [[P0443R14]]. [[#spec-execution]] is meant to be added as a new library clause to the working draft of C++. -# Exception handling [except] # {#spec-except} - -## Special functions [except.special] ## {#spec-except.special} +
+

+

+

+

+

+

+

+
-### General [except.special.general] ### {#spec-except.special.general} +
+# Exception handling [except] # {#spec-except} + +## Special functions [except.special] ## {#spec-except.special} -#### The `std::terminate` function [except.terminate] #### {#spec-except.terminate} + +### The `std::terminate` function [except.terminate] ### {#spec-except.terminate} -
At the end of the bulleted list in the Note in paragraph 1, add -a new bullet as follows:
+At the end of the bulleted list in the Note in paragraph 1, add +a new bullet as follows: - -
+
+* when a call to a `wait()`, `wait_until()`, or `wait_for()` function on a + condition variable (33.7.4, 33.7.5) fails to meet a postcondition. - - when a callback invocation exits via an exception when requesting stop on a +
+* when a callback invocation exits via an exception when requesting stop on a `std::stop_source` or a `std::in_place_stop_source` ([stopsource.mem], [stopsource.inplace.mem]), or in the constructor of `std::stop_callback` or `std::in_place_stop_callback` ([stopcallback.cons], [stopcallback.inplace.cons]) when a callback invocation exits via an exception. -
-
+
+ + + + +
# Library introduction [library] # {#spec-library} -
Add the header `` to Table 23: C++ library -headers [tab:headers.cpp]
+At the end of [expos.only.entity], add the following: -
At the end of [expos.only.entity], add the following:
+2. The following are defined for exposition only to aid in the specification of + the library: - -
+
+    namespace std {
+      // ...as before...
+    }
+    
+
3. An object `dst` is said to be decay-copied from a subexpression `src` if the type of `dst` is `decay_t`, and `dst` is copy-initialized from `src`. -
-
+
+ + + +
# General utilities library [utilities] # {#spec-utilities} + + ## Function objects [function.objects] ## {#spec-function.objects} + + ### Header `` synopsis [functional.syn] ### {#spec-functional.syn} -At the end of this subclause, insert the following declarations into the synopsis within `namespace std`: +At the end of this subclause, insert the following +declarations into the synopsis within `namespace std`: - -
-template<class Fn, class... Args>
-  concept callable =  // expositon only
-    requires (Fn&& fn, Args&&... args) {
-      std::forward<Fn>(fn)(std::forward<Args>(args)...);
-    };
-template<class Fn, class... Args>
-  concept nothrow-callable =   // expositon only
-    callable<Fn, Args...> &&
-    requires (Fn&& fn, Args&&... args) {
-      { std::forward<Fn>(fn)(std::forward<Args>(args)...) } noexcept;
-    };
-// expositon only:
-template<class Fn, class... Args>
-  using call-result-t = decltype(declval<Fn>()(declval<Args>()...));
+namespace std {
+  // ...as before...
+
+  namespace ranges {
+    // 22.10.9, concept-constrained comparisons
+    struct equal_to;                                    // freestanding
+    struct not_equal_to;                                // freestanding
+    struct greater;                                     // freestanding
+    struct less;                                        // freestanding
+    struct greater_equal;                               // freestanding
+    struct less_equal;                                  // freestanding
+  }
+
+
template<class Fn, class... Args> + concept callable = // exposition only + requires (Fn&& fn, Args&&... args) { + std::forward<Fn>(fn)(std::forward<Args>(args)...); + }; + template<class Fn, class... Args> + concept nothrow-callable = // exposition only + callable<Fn, Args...> && + requires (Fn&& fn, Args&&... args) { + { std::forward<Fn>(fn)(std::forward<Args>(args)...) } noexcept; + }; + // exposition only: + template<class Fn, class... Args> + using call-result-t = decltype(declval<Fn>()(declval<Args>()...)); -template<auto& Tag> - using tag_t = decltype(auto(Tag)); + template<const auto& Tag> + using decayed-typeof = decltype(auto(Tag)); // exposition only
+}
-
-
+
+ + + +
+# Concurrency support library [thread] # {#spec-thread} -# Thread support library [thread] # {#spec-thread} + ## Stop tokens [thread.stoptoken] ## {#spec-thread.stoptoken} -### Header `` synopsis [thread.stoptoken.syn] ### {#spec-thread.stoptoken.syn} +### Introduction [thread.stoptoken.intro] ### {#spec-thread.stoptoken.intro} + +1. Subclause [thread.stoptoken] describes components that can be used to + asynchronously request that an operation stops execution in a timely manner, + typically because the result is no longer required. Such a request is called + a stop request. + +2. stoppable_source, + stoppable_token, and + stoppable_callback implementare + concepts that specify the required syntax and semantics of + shared ownershipaccess of a stop + state. Any stoppable_source, + stoppable_token, or + stoppable_callback that shares ownership + ofrefers to the same stop state is an associated stoppable_source, + stoppable_token, or + stoppable_callback, respectively. The last + remaining owner of the stop state automatically releases the resources + associated with the stop state. + +3. A stoppable_token can be passed to an operation + whichthat can either + +
+ + * actively poll the token to check if there has been a stop request, or + + * register a callback using the stop_callback class + template whichthat will be called in the event that a + stop request is made.
+ + A stop request made via a stoppable_source will be + visible to all associated stoppable_token and + stoppable_source objects. Once a stop request has + been made it cannot be withdrawn (a subsequent stop request has no effect). -At the beginning of this subclause, insert the following declarations into the synopsis within `namespace std`: +4. Callbacks registered via a stoppable_callback object + are called when a stop request is first made by any associated + stoppable_source object. - -
-
-template<template<class> class>
-  struct check-type-alias-exists; // exposition-only
+The following paragraph is moved to the specification of
+the new `stoppable_source` concept.
 
-template<class T>
-  concept stoppable_token = see below;
+
-template<class T, class CB, class Initializer = CB> - concept stoppable_token_for = see below; +5. Calls to the functions `request_stop`, `stop_requested`, and `stop_possible` + do not introduce data races. A call to `request_stop` that returns `true` + synchronizes with a call to `stop_requested` on an associated + stoppable_token or + stoppable_source object that returns `true`. + Registration of a callback synchronizes with the invocation of that + callback. -template<class T> - concept unstoppable_token = see below; -
-
-
+
+ +
+ +5. The types `stop_source` and `stop_token` and the class template + `stop_callback` implement the semantics of shared ownership of a stop state. + The last remaining owner of the stop state automatically releases the + resources associated with the stop state. -At the end of this subclause, insert the following declarations into the synopsis of within `namespace std`: +6. The types `in_place_stop_source` and `in_place_stop_token` and the class + template `in_place_stop_callback` do no dynamic memory allocation or reference + counting of the stop state. They are for use when the lifetimes of the tokens + and the callbacks are known to nest within the lifetime of the source. + +
+ +### Header `` synopsis [thread.stoptoken.syn] ### {#spec-thread.stoptoken.syn} + +In this subclause, insert the following +declarations into the `` synopsis: - -
-// [stoptoken.never], class never_stop_token
-class never_stop_token;
+namespace std {
+
// [thread.stoptoken.concepts], stop token concepts + template<class T> + concept stoppable_token = see below; -// [stoptoken.inplace], class in_place_stop_token -class in_place_stop_token; + template<class T> + concept unstoppable_token = see below; + + template<class T> + concept stoppable_source = see below; + + template<class T> + concept stoppable_callback = see below;
+ // 33.3.3, class stop_token + class stop_token; -// [stopsource.inplace], class in_place_stop_source -class in_place_stop_source; + // 33.3.4, class stop_source + class stop_source; -// [stopcallback.inplace], class template in_place_stop_callback -template<class CB> - class in_place_stop_callback; + // no-shared-stop-state indicator + struct nostopstate_t { + explicit nostopstate_t() = default; + }; + inline constexpr nostopstate_t nostopstate{}; -template<class T, class CB> - using stop_callback_for_t = T::template callback_type<CB>; -
-
-
+ // 33.3.5, class template stop_callback + template<class Callback> + class stop_callback; -### Stop token concepts [thread.stoptoken.concepts] ### {#spec-thread.stoptoken.concepts} +
// [stoptoken.never], class never_stop_token + class never_stop_token; -Insert this subclause as a new subclause between Header `` synopsis -[thread.stoptoken.syn] and Class `stop_token` [stoptoken]. + // [stoptoken.inplace], class in_place_stop_token + class in_place_stop_token; - -
-1. The `stoppable_token` concept checks for the basic interface of a stop token - that is copyable and allows polling to see if stop has been requested and - also whether a stop request is possible. For a stop token type `T` and a type - `CB` that is callable with no arguments, the type `T::callback_type` is - valid and denotes the stop callback type to use to register a callback - to be executed if a stop request is ever made on a `stoppable_token` of type - `T`. The `stoppable_token_for` concept checks for a stop token type compatible - with a given callback type. The `unstoppable_token` concept checks for a stop - token type that does not allow stopping. + // [stopsource.inplace], class in_place_stop_source + class in_place_stop_source; -
-template<class T>
-  concept stoppable_token =
-    copyable<T> &&
-    equality_comparable<T> &&
-    requires (const T t) {
-      { T(t) } noexcept; // see implicit expression variations ([concepts.equality])
-      { t.stop_requested() } noexcept -> same_as<bool>;
-      { t.stop_possible() } noexcept -> same_as<bool>;
-      typename check-type-alias-exists<T::template callback_type>;
-    };
+  // [stopcallback.inplace], class template in_place_stop_callback
+  template<class Fun>
+    class in_place_stop_callback;
 
-template<class T, class CB, class Initializer = CB>
-  concept stoppable_token_for =
-    stoppable_token<T> &&
-    invocable<CB> &&
-    constructible_from<CB, Initializer> &&
-    requires { typename stop_callback_for_t<T, CB>; } &&
-    constructible_from<stop_callback_for_t<T, CB>, const T&, Initializer>;
-
-template<class T>
-  concept unstoppable_token =
-    stoppable_token<T> &&
-    requires {
-      { bool_constant<T::stop_possible()>{} } -> same_as<false_type>;
-    };
+  template<class T, class Fun>
+    using stop_callback_for_t = T::template callback_type<Fun>;
+}
+ -
LWG directed me to replace `T::stop_possible()` with -`t.stop_possible()` because of the recent `constexpr` changes in -[[P2280r2|P2280R2]]. However, even with those changes, a nested requirement like -`requires (!t.stop_possible())`, where `t` is an argument in the -requirement-parameter-list, is ill-formed according to [expr.prim.req.nested/p2]: -> A local parameter shall only appear as an unevaluated operand within the -> constraint-expression. +Insert the following subclause as a new subclause between +Header `` synopsis [thread.stoptoken.syn] and Class +`stop_token` [stoptoken]. +
+
-This is the subject of core issue [[cwg2517|2517]]. -
+### Stop token concepts [thread.stoptoken.concepts] ### {#spec-thread.stoptoken.concepts} + +1. The `stoppable_token` concept checks for the basic interface of a stop token + that is copyable and allows polling to see if stop has been requested and + also whether a stop request is possible. For a stop token type `Token` and a + type `Fun` that is callable with no arguments, if the type + `stop_callback_for_t` is valid, it denotes the type of a stop + callback to use to register a callback to be executed if a stop request is + ever made on the `stoppable_token`'s associated stop source. The + exposition-only `stoppable-token-for` concept checks for a stop token + type compatible with a given callback type. The `unstoppable_token` concept + checks for a stop token type that does not allow stopping. -2. Let `t` and `u` be distinct, valid objects of type `T`. The type `T` models - `stoppable_token` only if: +
+    template<template<class> class>
+      struct check-type-alias-exists; // exposition-only
+
+    template<class Token, class Fun, class Initializer = Fun>
+      concept stoppable-token-for = // exposition only
+        invocable<Fun> &&
+        constructible_from<Fun, Initializer> &&
+        requires { typename stop_callback_for_t<Token, Fun>; } &&
+        constructible_from<stop_callback_for_t<Token, Fun>, const Token&, Initializer>;
+
+    template<class Token>
+      concept stoppable_token =
+        requires (const Token tok) {
+          typename check-type-alias-exists<Token::template callback_type>;
+          { tok.stop_requested() } noexcept -> same_as<bool>;
+          { tok.stop_possible() } noexcept -> same_as<bool>;
+          { Token(tok) } noexcept; // see implicit expression variations
+                                   // ([concepts.equality])
+        } &&
+        copyable<Token> &&
+        equality_comparable<Token> &&
+        swappable;
+
+    template<class Token>
+      concept unstoppable_token =
+        stoppable_token<Token> &&
+        requires (const Token tok) {
+          requires bool_constant<(!tok.stop_possible())>::value;
+        };
+    
- 1. If `t.stop_possible()` evaluates to `false` then, if `t` and `u` - reference the same logical shared stop state, `u.stop_possible()` shall - also subsequently evaluate to `false` and `u.stop_requested()` shall also - subsequently evaluate to `false`. +2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the + same logical shared stop state; let `init` be an object of type `Initializer`; + let `Fun` be a type such that invocable<Fun> is `true`; and + let `CB` denote the type `stop_callback_for_t`. - 2. If `t.stop_requested()` evaluates to `true` then, if `t` and `u` - reference the same logical shared stop state, `u.stop_requested()` shall - also subsequently evaluate to `true` and `u.stop_possible()` shall also - subsequently evaluate to `true`. +3. The exposition-only concept stoppable-token-for<Token, Fun, + Initializer> is modeled only if: -3. Let `t` and `u` be distinct, valid objects of type `T` and let `init` be an - object of type `Initializer`. Then for some type `CB`, the type `T` models - `stoppable_token_for` only if: + 1. The following concepts are modeled: - 1. The type `T::callback_type` models: + * `constructible_from` + * `constructible_from` + * `constructible_from` - ```c++ - constructible_from && - constructible_from && - constructible_from - ``` + 2. Direct-non-list-initializing an object `cb` of type `CB` from arguments + `t` and `init` behaves as follows: - 2. Direct non-list initializing an object `cb` of type `T::callback_type` - from `t, init` shall, if `t.stop_possible()` is `true`, construct an - instance, `callback`, of type `CB`, direct-initialized with `init`, - and register callback with `t`'s shared stop state such that `callback` - will be invoked with an empty argument list if a stop request is made - on the shared stop state. + 1. If `t.stop_possible()` is `false`, it is unspecified whether the + initialization of `cb` causes the construction of an instance of + type `Fun`. - 1. If `t.stop_requested()` evaluates to `true` at the time `callback` is - registered then `callback` can be invoked on the thread executing - `cb`'s constructor. + 2. Otherwise, if `t.stop_possible()` is `true`: - 2. If `callback` is invoked then, if `t` and `u` reference the same - shared stop state, an evaluation of `u.stop_requested()` will be - `true` if the beginning of the invocation of `callback` - strongly-happens-before the evaluation of `u.stop_requested()`. + 1. an instance `fun` of type `Fun` is direct-initialized with `init`, + and - 3. If `t.stop_possible()` evaluates to `false` - then the construction of `cb` is not required to construct and - initialize `callback`. + 2. `fun` is registered with `t`'s shared stop state such that `fun` + will be invoked with an empty argument list if a stop request is + made on the shared stop state. - 3. Construction of a `T::callback_type` instance shall only throw - exceptions thrown by the initialization of the `CB` instance from the - value of type `Initializer`. + 3. If `t.stop_requested()` evaluates to `true` at the time `fun` is + registered then `fun` can be invoked on the thread executing + `cb`'s constructor. - 4. Destruction of the `T::callback_type` object, `cb`, removes - `callback` from the shared stop state such that `callback` will not be - invoked after the destructor returns. + 4. Construction of `cb` shall only throw exceptions thrown by the + initialization of `fun` from `init`. - 1. If `callback` is currently being invoked on another thread then the - destructor of `cb` will block until the invocation of `callback` - returns such that the return from the invocation of `callback` - strongly-happens-before the destruction of `callback`. + 3. An evaluation of `u.stop_requested()` that strongly happens after + ([intro.races]/10) the beginning of the invocation of `fun` will return + `true`. + + 4. Destruction of `cb` removes `fun` from the shared stop state. + + 1. If `fun` is currently being invoked on another thread then the + destructor of `cb` will block until the invocation of `fun` returns + such that the return from the invocation of `fun` + strongly-happens-before the destruction of `fun`. 2. Destruction of a callback `cb` shall not block on the completion of the invocation of some other callback registered with the same shared stop state. - - +4. The type `Token` models `stoppable_token` only if: + + 1. If an evaluation, `E`, of `t.stop_possible()` evaluates to `false`, then + evaluations of `u.stop_possible()` and `u.stop_requested()` that happen + after `E` shall evaluate to `false`. + + 2. If an evaluation, `E`, of `t.stop_requested()` evaluates to `true`, then + evaluations of `u.stop_possible()` and `u.stop_requested()` that happens + after `E` shall evaluate to `true`. + + 3. For any types `Fun` and `Initializer`, if `invocable && + constructible_from` is `true` and the type `CB` is + well-formed, then the concept stoppable-token-for<Token, + Fun, Initializer> shall be modeled. + + 4. A `stoppable_token` object has at most one associated logical stop state. + A `stoppable_token` object with no associated stop state is said to be + disengaged. For a disengaged `stoppable_token` + object, `stop_possible` and `stop_requested` shall return `false`. If + `t` and `u` reference the same stop state, or if both `t` and `u` are + disengaged, `t == u` shall be `true`; otherwise, it shall be `false`. + +5. A model of `stoppable_source` can be queried whether stop has been requested + (`stop_requested`) and whether stop is possible (`stop_possible`). It is a + factory for associated stop tokens (`get_token`) and can be explicitly + placed into the "stop requested" state (`request_stop`). It maintains a list + of registered stop callback invocations that it executes when a stop request + is first made. + +
+    template<class Source>
+      concept stoppable_source =
+        requires (Source& src, const Source csrc) { // see implicit expression variations
+                                                    // ([concepts.equality])
+          { csrc.get_token() } -> stoppable_token;
+          { csrc.stop_possible() } noexcept -> same_as<bool>;
+          { csrc.stop_requested() } noexcept -> same_as<bool>;
+          { src.request_stop() } -> same_as<bool>;
+        };
+    
+ + 1. A `stoppable_source` object has at most one associated logical stop + state. A `stoppable_source` object with no associated stop state is said + to be disengaged. For a disengaged `stoppable_source` object, + `stop_possible` and `stop_requested` shall return `false`. + + 2. A stop token returned from `get_token()` is associated with the stop state + of the source. + + 3. The registration of a callback invocation either succeeds or fails. When + an invocation of a callback is registered, the following happens + atomically: + + - The stop state is checked. If stop has not been requested, the + callback invocation is added to the list of registered callback + invocations, and registration has succeeded. + + - Otherwise, registration has failed. + + 4. When an invocation of a callback is unregistered, the invocation is + atomically removed from the list of registered callback invocations. The + removal is not blocked by the concurrent execution of another callback + invocation in the list. If the callback invocation being unregistered is + currently executing, then: + + - If the execution of the callback invocation is happening concurrently + on another thread, the completion of the execution strongly happens + before ([intro.races]) the end of the callback's lifetime. + + - Otherwise, the execution is happening on the current thread. Removal + of the callback invocation does not block waiting for the execution to + complete. + + The following paragraph is moved from the introduction, + with minor modifications (underlined in green). + 5. Calls to the member functions `request_stop`, + `stop_requested`, and `stop_possible` and similarly named member + functions on associated `stoppable_token` objects do not introduce + data races. A call to `request_stop` that returns `true` synchronizes + with a call to `stop_requested` on an associated + stoppable_token or + stoppable_source object that returns `true`. + Registration of a callback synchronizes with the invocation of that + callback. + +
+
+ +Modify subclause [stoptoken] as follows: + +
### Class `stop_token` [stoptoken] ### {#spec-stoptoken} #### General [stoptoken.general] #### {#spec-stoptoken.general} -Modify the synopsis of class `stop_token` in subclause General -[stoptoken.general] as follows: +1. The class `stop_token` provides an interface for querying whether a stop + request has been made (`stop_requested`) or can ever be made (`stop_possible`) + using an associated `stop_source` object ([stopsource]). A `stop_token` can also be + passed to a `stop_callback` ([stopcallback]) constructor to register a callback to be + called when a stop request has been made from an associated + `stop_source`.The class `stop_token` models the concept + `stoppable_token`. It shares ownership of its stop state, if any, with its + associated `stop_source` object ([stopsource]) and any `stop_token` objects + to which it compares equal.
 namespace std {
   class stop_token {
   public:
-    template<class T>
-      using callback_type = stop_callback<T>;
+
template<class T> + using callback_type = stop_callback<T>;
+ // [stoptoken.cons], constructors, copy, and assignment + stop_token() noexcept = default; + +
stop_token(const stop_token&) noexcept; + stop_token(stop_token&&) noexcept; + stop_token& operator=(const stop_token&) noexcept; + stop_token& operator=(stop_token&&) noexcept; + ~stop_token();
+ + // [stoptoken.mem], Member functions + void swap(stop_token&) noexcept; + + // [stoptoken.mem], stop handling + [[nodiscard]] bool stop_requested() const noexcept; + [[nodiscard]] bool stop_possible() const noexcept; + + bool operator==(const stop_token& rhs) const noexcept = default; + [[nodiscard]] friend bool operator==(const stop_token& lhs, const stop_token& rhs) noexcept; + friend void swap(stop_token& lhs, stop_token& rhs) noexcept; + private: + shared_ptr<unspecified> stop-state{}; // exposition only + }; +} +
+ +
+ +1. `stop-state` refers to the `stop_token`'s associated stop state. A + `stop_token` object is disengaged when `stop-state` is null.
+ +
- // [stoptoken.cons], constructors, copy, and assignment - stop_token() noexcept; +
+#### Constructors, copy, and assignment [stoptoken.cons] #### {#spec-stoptoken.cons} - // ... +
+stop_token() noexcept;
 
-### Class `never_stop_token` [stoptoken.never] ### {#spec-stoptoken.never} +1. *Postconditions:* `stop_possible()` is `false` and `stop_requested()` is + `false`. Because the created `stop_token` + object can never receive a stop request, no resources are allocated for a + stop state. + +
+stop_token(const stop_token& rhs) noexcept;
+
-Insert a new subclause, Class `never_stop_token` [stoptoken.never], after -subclause Class template `stop_callback` [stopcallback], as a new -subclause of Stop tokens [thread.stoptoken]. +2. *Postconditions:* `*this == rhs` is `true`. `*this` + and `rhs` share the ownership of the same stop state, if any. -#### General [stoptoken.never.general] #### {#spec-stoptoken.never.general} +
+stop_token(stop_token&& rhs) noexcept;
+
-1. The class `never_stop_token` provides an implementation of the - `unstoppable_token` concept. It provides a stop token interface, but also - provides static information that a stop is never possible nor requested. +3. *Postconditions:* `*this` contains the value of `rhs` prior to the start of + construction and `rhs.stop_possible()` is `false`.
-namespace std
-{
-  class never_stop_token {
-    // exposition only
-    struct callback {
-      explicit callback(never_stop_token, auto&&) noexcept {}
-    };
-  public:
-    template<class>
-      using callback_type = callback;
+~stop_token();
+
- [[nodiscard]] static constexpr bool stop_requested() noexcept { return false; } - [[nodiscard]] static constexpr bool stop_possible() noexcept { return false; } +4. *Effects:* Releases ownership of the stop state, if any. - [[nodiscard]] friend bool operator==(const never_stop_token&, const never_stop_token&) noexcept = default; - }; -} +
+stop_token& operator=(const stop_token& rhs) noexcept;
 
-### Class `in_place_stop_token` [stoptoken.inplace] ### {#spec-stoptoken.inplace} +5. *Effects:* Equivalent to: `stop_token(rhs).swap(*this)`. -Insert a new subclause, Class `in_place_stop_token` [stoptoken.inplace], -after the subclause added above, as a new subclause of Stop tokens -[thread.stoptoken]. +6. *Returns:* `*this`. -#### General [stoptoken.inplace.general] #### {#spec-stoptoken.inplace.general} +
+stop_token& operator=(stop_token&& rhs) noexcept;
+
+ +7. *Effects:* Equivalent to: `stop_token(std::move(rhs)).swap(*this)`. + +8. *Returns:* `*this`. + +
-1. The class `in_place_stop_token` provides an interface for querying whether a - stop request has been made (`stop_requested`) or can ever be made - (`stop_possible`) using an associated `in_place_stop_source` object - ([stopsource.inplace]). An `in_place_stop_token` can also be passed to an - `in_place_stop_callback` ([stopcallback.inplace]) constructor to register a - callback to be called when a stop request has been made from an associated - `in_place_stop_source`. +Move `swap` into [stoptoken.mem]: + +#### Member functions [stoptoken.mem] #### {#spec-stoptoken.mem}
-namespace std {
-  class in_place_stop_token {
-  public:
-    template<class CB>
-      using callback_type = in_place_stop_callback<CB>;
+void swap(stop_token& rhs) noexcept;
+
- // [stoptoken.inplace.cons], constructors, copy, and assignment - in_place_stop_token() noexcept; - ~in_place_stop_token(); - void swap(in_place_stop_token&) noexcept; +1. *Effects:* Exchanges the values of `*this` and `rhs`. Equivalent to: + std::swap(stop-state, rhs.stop-state). - // [stoptoken.inplace.mem], stop handling - [[nodiscard]] bool stop_requested() const noexcept; - [[nodiscard]] bool stop_possible() const noexcept; +
+[[nodiscard]] bool stop_requested() const noexcept;
+
+ +2. *Returns:* `true` if `*this` has ownership + of`stop-state` refers to a stop state that has + received a stop request; otherwise, `false`. + +
+[[nodiscard]] bool stop_possible() const noexcept;
+
+ +3. *Returns:* `false` if: + +
+ + * `*this` does not have ownership of a stop stateis disengaged, or + + * a stop request was not made and there are no associated `stop_source` + objects; otherwise, `true`. - [[nodiscard]] friend bool operator==(const in_place_stop_token&, const in_place_stop_token&) noexcept = default; - friend void swap(in_place_stop_token& lhs, in_place_stop_token& rhs) noexcept; +
+ +The following are covered by the `equality_comparable` and +`swappable` concepts. + +
+#### Non-member functions [stoptoken.nonmembers] #### {#spec-stoptoken.nonmembers} + +
+[[nodiscard]] bool operator==(const stop_token& lhs, const stop_token& rhs) noexcept;
+
+ +1. *Returns:* `true` if `lhs` and `rhs` have ownership of the same stop state or + if both `lhs` and `rhs` do not have ownership of a stop state; otherwise + `false`. + +
+friend void swap(stop_token& x, stop_token& y) noexcept;
+
- private: - const in_place_stop_source* source_; // exposition only +2. *Effects:* Equivalent to: `x.swap(y)`. + +
+ +
+### Class `stop_source` [stopsource] ### {#spec-stopsource} + +#### General [stopsource.general] #### {#spec-stopsource.general} + +1. The class `stop_source` implements the semantics of making a stop + request. A stop request made on a `stop_source` object is visible to all + associated `stop_source` and `stop_token` ([thread.stoptoken]) objects. Once + a stop request has been made it cannot be withdrawn (a subsequent stop + request has no effect)models `stoppable_source`. + +
+namespace std {
+  The following definitions are already specified in the `` synopsis:
+
// no-shared-stop-state indicator + struct nostopstate_t { + explicit nostopstate_t() = default; + }; + inline constexpr nostopstate_t nostopstate{};
+ + class stop_source { + public: + // 33.3.4.2, constructors, copy, and assignment + stop_source(); + explicit stop_source(nostopstate_t) noexcept; {} + +
stop_source(const stop_source&) noexcept; + stop_source(stop_source&&) noexcept; + stop_source& operator=(const stop_source&) noexcept; + stop_source& operator=(stop_source&&) noexcept; + ~stop_source();
+ + // [stopsource.mem], Member functions + void swap(stop_source&) noexcept; + + // 33.3.4.3, stop handling + [[nodiscard]] stop_token get_token() const noexcept; + [[nodiscard]] bool stop_possible() const noexcept; + [[nodiscard]] bool stop_requested() const noexcept; + bool request_stop() noexcept; + + bool operator==(const stop_source& rhs) const noexcept = default; +
[[nodiscard]] friend bool + operator==(const stop_source& lhs, const stop_source& rhs) noexcept; + friend void swap(stop_source& lhs, stop_source& rhs) noexcept;
+ private: + shared_ptr<unspecified> stop-state{}; // exposition only }; }
-#### Constructors, copy, and assignment [stoptoken.inplace.cons] #### {#spec-stoptoken.inplace.cons} +
+1. `stop-state` refers to the `stop_source`'s associated stop state. A + `stop_source` object is disengaged when `stop-state` is null. + +2. `stop_source` models `copyable`, `equality_comparable`, and `swappable`. + +
+ +#### Constructors, copy, and assignment [stopsource.cons] #### {#spec-stopsource.cons}
-in_place_stop_token() noexcept;
+stop_source();
 
-1. *Effects*: initializes source_ with `nullptr`. +1. *Effects:* Initialises `*this` to have ownership + of`stop-state` with a pointer to a new stop state. + +2. *Postconditions:* `stop_possible()` is `true` and `stop_requested()` is `false`. +3. *Throws:* `bad_alloc` if memory cannot be allocated for the stop state. + +
-void swap(stop_token& rhs) noexcept;
+explicit stop_source(nostopstate_t) noexcept;
 
-2. *Effects*: Exchanges the values of source_ and - rhs.source_. +4. *Postconditions:* `stop_possible()` is `false` and `stop_requested()` is `false`. + No resources are allocated for the state. + +
+stop_source(const stop_source& rhs) noexcept;
+
+ +5. *Postconditions:* `*this` == rhs is `true`. + `*this` and `rhs` share the ownership of the same stop state, if any. + +
+stop_source(stop_source&& rhs) noexcept;
+
+ +6. *Postconditions:* `*this` contains the value of `rhs` prior to the start of construction and + `rhs.stop_possible()` is `false`. + +
+~stop_source();
+
+ +7. *Effects:* Releases ownership of the stop state, if any. + +
+stop_source& operator=(const stop_source& rhs) noexcept;
+
+ +8. *Effects:* Equivalent to: `stop_source(rhs).swap(*this)`. + +9. *Returns:* `*this`. + +
+stop_source& operator=(stop_source&& rhs) noexcept;
+
+ +10. *Effects:* Equivalent to: `stop_source(std::move(rhs)).swap(*this)`. + +11. *Returns:* `*this`. + +
+ +Move `swap` into [stopsource.mem]: + +#### Member functions [stopsource.mem] #### {#spec-stopsource.mem} + +
+void swap(stop_source& rhs) noexcept;
+
+ +12. *Effects:* Exchanges the values of `*this` and `rhs`Equivalent to: + std::swap(stop-state, rhs.stop-state). + +
+[[nodiscard]] stop_token get_token() const noexcept;
+
+ +1. *Returns:* `stop_token()` if `stop_possible()` is `false`; otherwise a new + associated `stop_token` object; *i.e.*, its `stop-state` pointer + is equal to the `stop-state` pointer of `*this`. + +
+[[nodiscard]] bool stop_possible() const noexcept;
+
+ +2. *Returns:* `true` if `*this` has ownership of a stop state; otherwise, + `false`stop-state != nullptr. + +
+[[nodiscard]] bool stop_requested() const noexcept;
+
+ +3. *Returns:* `true` if `*this` has ownership + of`stop-state` refers to a stop state that has + received a stop request; otherwise, `false`. + +
+bool request_stop() noexcept;
+
+ +4. *Effects:* If `*this` does not have ownership of a stop + state`stop-state` is null, returns `false`. + Otherwise, atomically determines whether the owned stop state has received a + stop request, and if not, makes a stop request. The determination and making + of the stop request are an atomic read-modify-write operation + ([intro.races]). If the request was made, the callbacks registered by + associated `stop_callback` objects are synchronously called. If an + invocation of a callback exits via an exception then `terminate` is invoked + ([except.terminate]). + + A stop request includes notifying all condition + variables of type `condition_variable_any` temporarily registered during an + interruptible wait ([thread.condvarany.intwait]). + +5. *Postconditions:* `stop_possible()` is `false` or `stop_requested()` is + `true`. + +6. *Returns:* `true` if this call made a stop request; otherwise `false`. + +
+#### Non-member functions [stopsource.nonmembers] #### {#spec-stopsource.nonmembers} + +
+[[nodiscard]] friend bool
+  operator==(const stop_source& lhs, const stop_source& rhs) noexcept;
+
+ +1. *Returns:* `true` if `lhs` and `rhs` have ownership of the same stop state or if + both `lhs` and `rhs` do not have ownership of a stop state; otherwise `false`. + +
+friend void swap(stop_source& x, stop_source& y) noexcept;
+
+ +2. *Effects:* Equivalent to: `x.swap(y)`. + +
+
+ + + +Insert a new subclause, Class `never_stop_token` +[stoptoken.never], after subclause Class template `stop_callback` +[stopcallback], as a new subclause of Stop tokens +[thread.stoptoken]. +
+
+### Class `never_stop_token` [stoptoken.never] ### {#spec-stoptoken.never} + +#### General [stoptoken.never.general] #### {#spec-stoptoken.never.general} + +1. The class `never_stop_token` models the `unstoppable_token` concept. It + provides a stop token interface, but also provides static information that a + stop is never possible nor requested. + +
+    namespace std {
+      class never_stop_token {
+        struct callback { // exposition only
+          explicit callback(never_stop_token, auto&&) noexcept {}
+        };
+      public:
+        template<class>
+          using callback_type = callback;
+
+        static constexpr bool stop_requested() noexcept { return false; }
+        static constexpr bool stop_possible() noexcept { return false; }
+
+        bool operator==(const never_stop_token&) const noexcept = default;
+      };
+    }
+    
+
+
+ +Insert a new subclause, Class `in_place_stop_token` +[stoptoken.inplace], after the subclause added above, as a new subclause +of Stop tokens [thread.stoptoken]. +
+
+### Class `in_place_stop_token` [stoptoken.inplace] ### {#spec-stoptoken.inplace} + +#### General [stoptoken.inplace.general] #### {#spec-stoptoken.inplace.general} + +1. The class `in_place_stop_token` models the concept `stoppable_token`. It + references the stop state of its associated `in_place_stop_source` object + ([stopsource.inplace]), if any. + +
+    namespace std {
+      class in_place_stop_token {
+      public:
+        template<class CB>
+          using callback_type = in_place_stop_callback<CB>;
 
-#### Members [stoptoken.inplace.mem] #### {#spec-stoptoken.inplace.mem}
+        in_place_stop_token() noexcept = default;
+        bool operator==(const in_place_stop_token&) const noexcept = default;
+
+        // [stoptoken.inplace.mem], member functions
+        bool stop_requested() const noexcept;
+        bool stop_possible() const noexcept;
+        void swap(in_place_stop_token&) noexcept;
+
+        // [stoptoken.inplace.special], specialized algorithms
+        friend void swap(in_place_stop_token& lhs, in_place_stop_token& rhs) noexcept;
+
+      private:
+        const in_place_stop_source* stop-source = nullptr; // exposition only
+      };
+    }
+    
+ +#### Member functions [stoptoken.inplace.members] #### {#spec-stoptoken.inplace.members}
-[[nodiscard]] bool stop_requested() const noexcept;
+void swap(in_place_stop_token& rhs) noexcept;
 
-1. *Effects*: Equivalent to: return source_ != nullptr && - source_->stop_requested(); +1. *Effects*: Exchanges the values of stop-source and + rhs.stop-source. -2. The behavior of `stop_requested()` is undefined unless - the call strongly happens before the start of the destructor of the - associated `in_place_stop_source`, if any ([basic.life]). +
+bool stop_requested() const noexcept;
+
+ +1. *Effects*: Equivalent to: return stop-source != nullptr && + stop-source->stop_requested(); + +2. As specified in [basic.life], the behavior of + `stop_requested()` is undefined unless the call strongly happens before the + start of the destructor of the associated `in_place_stop_source`, if + any.
-[[nodiscard]] bool stop_possible() const noexcept;
+bool stop_possible() const noexcept;
 
-3. *Effects*: Equivalent to: return source_ != nullptr; +3. *Returns*: stop-source != nullptr. -4. The behavior of `stop_possible()` is - implementation-defined unless the call strongly happens before the end of - the storage duration of the associated `in_place_stop_source` object, if any - ([basic.stc.general]). +4. As specified in [basic.stc.general], the behavior of + `stop_possible()` is implementation-defined unless the call strongly happens + before the end of the storage duration of the associated + `in_place_stop_source` object, if any. -#### Non-member functions [stoptoken.inplace.nonmembers] #### {#spec-stoptoken.inplace.nonmembers} +#### Specialized algorithms [stoptoken.inplace.special] #### {#spec-stoptoken.inplace.special}
 friend void swap(in_place_stop_token& x, in_place_stop_token& y) noexcept;
 
-2. *Effects*: Equivalent to: `x.swap(y)`. +2. *Effects*: Equivalent to: `x.swap(y);` -### Class `in_place_stop_source` [stopsource.inplace] ### {#spec-stopsource.inplace} +
+
-Insert a new subclause, Class `in_place_stop_source` +Insert a new subclause, Class `in_place_stop_source` [stopsource.inplace], after the subclause added above, as a new subclause -of Stop tokens [thread.stoptoken]. +of Stop tokens [thread.stoptoken]. +
+
+### Class `in_place_stop_source` [stopsource.inplace] ### {#spec-stopsource.inplace} #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general} 1. The class `in_place_stop_source` implements the semantics of making a stop request, without the need for a dynamic allocation of a shared state. A stop - request made on a `in_place_stop_source` object is visible to all associated - `in_place_stop_token` ([stoptoken.inplace]) objects. Once a stop request has - been made it cannot be withdrawn (a subsequent stop request has no effect). - All uses of `in_place_stop_token` objects associated with a given - `in_place_stop_source` object must happen before the start of the destructor - of that `in_place_stop_source` object. + request made on an `in_place_stop_source` object is visible to all + associated `in_place_stop_token` ([stoptoken.inplace]) objects. Once a stop + request has been made it cannot be withdrawn, and a subsequent stop request + has no effect. All uses of `in_place_stop_token` objects associated with a + given `in_place_stop_source` object shall happen before the start of the + destructor of that `in_place_stop_source` object. -
-namespace std {
-  class in_place_stop_source {
-  public:
-    // [stopsource.inplace.cons], constructors, copy, and assignment
-    in_place_stop_source() noexcept;
+    
+    namespace std {
+      class in_place_stop_source {
+      public:
+        // [stopsource.inplace.cons], constructors, copy, and assignment
+        in_place_stop_source() noexcept;
 
-    in_place_stop_source(in_place_stop_source&&) noexcept = delete;
-    ~in_place_stop_source();
+        in_place_stop_source(in_place_stop_source&&) noexcept = delete;
+        ~in_place_stop_source();
 
-    //[stopsource.inplace.mem], stop handling
-    [[nodiscard]] in_place_stop_token get_token() const noexcept;
-    [[nodiscard]] static constexpr bool stop_possible() noexcept { return true; }
-    [[nodiscard]] bool stop_requested() const noexcept;
-    bool request_stop() noexcept;
-  };
-}
-
+ //[stopsource.inplace.mem], stop handling + in_place_stop_token get_token() const noexcept; + static constexpr bool stop_possible() noexcept { return true; } + bool stop_requested() const noexcept; + bool request_stop() noexcept; + }; + } +
+ + NOTE: find a way to share this wording with `stop_source`. maybe as a StopSource concept? 2. An instance of `in_place_stop_source` maintains a list of registered callback invocations. The registration of a callback invocation either succeeds or @@ -4351,13 +4965,13 @@ in_place_stop_source() noexcept; #### Members [stopsource.inplace.mem] #### {#spec-stopsource.inplace.mem}
-[[nodiscard]] in_place_stop_token get_token() const noexcept;
+in_place_stop_token get_token() const noexcept;
 
1. *Returns*: A new associated `in_place_stop_token` object.
-[[nodiscard]] bool stop_requested() const noexcept;
+bool stop_requested() const noexcept;
 
3. *Returns*: `true` if the stop state inside `*this` has received a stop @@ -4379,11 +4993,16 @@ bool request_stop() noexcept; 6. *Returns*: `true` if this call made a stop request; otherwise `false`. -### Class template `in_place_stop_callback` [stopcallback.inplace] ### {#spec-stopcallback.inplace} +
+
+ +Insert a new subclause, Class template +`in_place_stop_callback` [stopcallback.inplace], after the subclause +added above, as a new subclause of Stop tokens [thread.stoptoken]. +
+
-Insert a new subclause, Class template `in_place_stop_callback` -[stopcallback.inplace], after the subclause added above, as a new -subclause of Stop tokens [thread.stoptoken]. +### Class template `in_place_stop_callback` [stopcallback.inplace] ### {#spec-stopcallback.inplace} #### General [stopcallback.inplace.general] #### {#spec-stopcallback.inplace.general} @@ -4405,7 +5024,7 @@ subclause of Stop tokens [thread.stoptoken]. in_place_stop_callback(in_place_stop_callback&&) = delete; private: - Callback callback_; // exposition only + Callback stop-callback; // exposition only }; template<class Callback> @@ -4422,6 +5041,11 @@ subclause of Stop tokens [thread.stoptoken]. for the template parameter `Callback` that models both `invocable` and `destructible`. +REWORD: + +*Remarks:* Implementations are not permitted to ....<blah blah> (from optional) + + 4. *Recommended practice*: Implementations should use the storage of the `in_place_stop_callback` objects to store the state necessary for their association with an `in_place_stop_source` object. @@ -4434,23 +5058,23 @@ template<class C> noexcept(is_nothrow_constructible_v<Callback, C>);
-1. *Constraints*: `Callback` and `C` satisfy `constructible_from`. +1. *Constraints*: `constructible_from` is modeled. -2. *Preconditions*: `Callback` and `C` model `constructible_from`. +SHARE THIS WORDING WITH STOP_TOKEN, MAYBE WITH A CONCEPT? -3. *Effects*: Initializes callback_ with +2. *Effects*: Initializes stop-callback with `std::forward(cb)`. Any `in_place_stop_source` associated with `st` becomes associated with `*this`. Registers ([stopsource.inplace.general]) the callback invocation - std::forward<Callback>(callback_)() with the + std::forward<Callback>(stop-callback)() with the associated `in_place_stop_source`, if any. If the registration fails, evaluates the callback invocation. -4. *Throws*: Any exception thrown by the initialization of - callback_. +3. *Throws*: Any exception thrown by the initialization of + stop-callback. -5. *Remarks*: If evaluating - std::forward<Callback>(callback_)() exits via an +4. *Remarks*: If evaluating + std::forward<Callback>(stop-callback)() exits via an exception, then `terminate` is invoked ([except.terminate]).
@@ -4460,10 +5084,18 @@ template<class C>
 6. *Effects*: Unregisters ([stopsource.inplace.general]) the callback invocation from
     the associated `in_place_stop_source` object, if any.
 
-7. *Remarks*: A program has undefined behavior if the start of this destructor does
+7. *Remarks*: A program has undefined behavior if the end of this destructor does
     not strongly happen before the start of the destructor of the associated
     `in_place_stop_source` object, if any.
 
+
+
+
+Insert a new top-level clause
+
+
+
+ # Execution control library [exec] # {#spec-execution} ## General [exec.general] ## {#spec-execution.general} @@ -5785,7 +6417,7 @@ enum class forward_progress_guarantee { Index, state-type<Sndr, Rcvr>&, Rcvr&, set_value_t, Args...> void set_value(Args&&... args) && noexcept { (void) impls-for<tag-type>::complete( - Index(), op_->state_, op_->rcvr_, set_value_t(), std::forward<Args>(args)...); + Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...); } template<class Error> @@ -5793,22 +6425,22 @@ enum class forward_progress_guarantee { Index, state-type<Sndr, Rcvr>&, Rcvr&, set_error_t, Error> void set_error(Error&& err) && noexcept { (void) impls-for<tag-type>::complete( - Index(), op_->state_, op_->rcvr_, set_error_t(), std::forward<Error>(err)); + Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err)); } void set_stopped() && noexcept requires cpo-callable<impls-for<tag-type>::complete, Index, state-type<Sndr, Rcvr>&, Rcvr&, set_stopped_t> { (void) impls-for<tag-type>::complete( - Index(), op_->state_, op_->rcvr_, set_stopped_t()); + Index(), op->state, op->rcvr, set_stopped_t()); } auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> { - const auto& rcvr = op_->rcvr_; - return impls-for<tag-type>::get-env(Index(), op_->state_, rcvr); + const auto& rcvr = op->rcvr; + return impls-for<tag-type>::get-env(Index(), op->state, rcvr); } - basic-operation<Sndr, Rcvr>* op_; // exposition only + basic-operation<Sndr, Rcvr>* op; // exposition only }; constexpr auto connect-all = // exposition only @@ -5836,19 +6468,19 @@ enum class forward_progress_guarantee { using operation_state_concept = operation_state_t; using tag-type = tag_of_t<Sndr>; // exposition only - Rcvr rcvr_; // exposition only - state-type<Sndr, Rcvr> state_; // exposition only - inner-ops-tuple<Sndr, Rcvr> inner_ops_; // exposition only + Rcvr rcvr; // exposition only + state-type<Sndr, Rcvr> state; // exposition only + inner-ops-tuple<Sndr, Rcvr> inner-ops; // exposition only - basic-operation(Sndr&& sndr, Rcvr rcvr) // exposition only - : rcvr_(std::move(rcvr)) - , state_(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr_)) - , inner_ops_(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>())) + basic-operation(Sndr&& sndr, Rcvr rcvr_init) // exposition only + : rcvr(std::move(rcvr_init)) + , state(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr)) + , inner-ops(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>())) {} void start() & noexcept { - auto& [...ops] = inner_ops_; - impls-for<tag-type>::start(state_, rcvr_, ops...); + auto& [...ops] = inner-ops; + impls-for<tag-type>::start(state, rcvr, ops...); } }; @@ -5906,7 +6538,7 @@ enum class forward_progress_guarantee {
               [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
                 if constexpr (sizeof...(child) == 1)
-                  return FWD-ENV(get_env(child...)); //
+                  return FWD-ENV(get_env(child...));
                 else
                   return empty_env();
               }
@@ -6064,12 +6696,12 @@ enum class forward_progress_guarantee {
 
       - Otherwise, `tag_of_t` is ill-formed.
 
-    
+ There is no way in standard C++ to determine whether the above declaration is well-formed without causing a hard error, so this presumes compiler magic. However, the author anticipates the adoption of [@P2141R1], which makes it possible to implement this purely in the library. P2141 has already - been approved by EWG for C++26.
+ been approved by EWG for C++26. 6. Let sender-for be an exposition-only concept defined as follows: @@ -6111,9 +6743,9 @@ enum class forward_progress_guarantee { picked by overload resolution if any, and any necessary implicit conversions and materializations. -
I have opened + I have opened [cwg#250](https://github.com/cplusplus/CWG/issues/250) to give these - transformations a term-of-art so we can more easily refer to it here.
+ transformations a term-of-art so we can more easily refer to it here. 3. Let is-awaitable be the following exposition-only concept: @@ -6351,7 +6983,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> a completion function. If sender `Sndr` or its operation state cause the expression CSO(rcvr, args...) to be potentially evaluated ([basic.def.odr]) then there shall be a signature `Sig` in `Sigs...` such - that MATCHING-SIG(tag_t<CSO>(decltype(args)...), + that + MATCHING-SIG(decayed-typeof<CSO>(decltype(args)...), Sig) is `true` ([exec.general]). ### `execution::connect` [exec.connect] ### {#spec-execution.senders.connect} @@ -6431,10 +7064,10 @@ template<class Domain, class Tag, sender Sndr, class... Args> auto fn = [&, fun]() noexcept { fun(std::forward<Ts>(as)...); }; struct awaiter { - decltype(fn) fn_; + decltype(fn) fn; static bool await_ready() noexcept { return false; } - void await_suspend(coroutine_handle<>) noexcept { fn_(); } + void await_suspend(coroutine_handle<>) noexcept { fn(); } [[noreturn]] void await_resume() noexcept { unreachable(); } }; return awaiter{fn}; @@ -6519,7 +7152,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         template<>
-        struct impls-for<tag_t<just-cpo>> : default-impls {
+        struct impls-for<decayed-typeof<just-cpo>> : default-impls {
           static constexpr auto start =
             [](auto& state, auto& rcvr) noexcept -> void {
               auto& [...ts] = state;
@@ -6543,7 +7176,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
     
     template<>
-    struct impls-for<tag_t<read>> : default-impls {
+    struct impls-for<decayed-typeof<read>> : default-impls {
       static constexpr auto start =
         [](auto query, auto& rcvr) noexcept -> void {
           TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
@@ -6949,11 +7582,11 @@ template<class Domain, class Tag, sender Sndr, class... Args>
 
         
         template<>
-        struct impls-for<tag_t<then-cpo>> : default-impls {
+        struct impls-for<decayed-typeof<then-cpo>> : default-impls {
           static constexpr auto complete =
             []<class Tag, class... Args>
               (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
-                if constexpr (same_as<Tag, tag_t<set-cpo>>) {
+                if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
                   TRY-SET-VALUE(std::move(rcvr),
                                 invoke(std::move(fn), std::forward<Args>(args)...));
                 } else {
@@ -6987,7 +7620,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     let-env(sndr) be expression-equivalent to the first
     well-formed expression below:
 
-      - SCHED-ENV(get_completion_scheduler<tag_t<set-cpo>>(get_env(sndr)))
+      - SCHED-ENV(get_completion_scheduler<decayed-typeof<set-cpo>>(get_env(sndr)))
 
       - MAKE-ENV(get_domain, get_domain(get_env(sndr)))
 
@@ -7018,7 +7651,7 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         void let-bind(State& state, Rcvr& rcvr, Args&&... args); // exposition only
 
         template<>
-        struct impls-for<tag_t<let-cpo>> : default-impls {
+        struct impls-for<decayed-typeof<let-cpo>> : default-impls {
           static constexpr auto get-state = see below;
           static constexpr auto complete = see below;
         };
@@ -7217,11 +7850,11 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     `constructible_from>, env_of_t>` is `false`,
     shared-cpo(sndr) is ill-formed.
 
-    
Although it has not yet been approved by LEWG, there + Although it has not yet been approved by LEWG, there is a bug in the current wording that makes it impossible to safely copy the attributes of a sender; it may have reference semantics, leading to a dangling reference. I am striking this part for now and will bring a fix to - LEWG.
+ LEWG. 4. Otherwise, the expression shared-cpo(sndr) is expression-equivalent to: @@ -7647,7 +8280,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> expression:
-          
BUG: `apply` isn't constrained
+ BUG: `apply` isn't constrained []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) -> decltype(apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr))) { return apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr)); @@ -8493,8 +9126,8 @@ template<class Domain, class Tag, sender Sndr, class... Args> class run-loop-sender; // exposition only struct run-loop-opstate-base { // exposition only virtual void execute() = 0; - run_loop* loop_; - run-loop-opstate-base* next_; + run_loop* loop; + run-loop-opstate-base* next; }; template<receiver_of<completion_signatures<set_value_t()>> Rcvr> using run-loop-opstate = unspecified; // exposition only @@ -8604,7 +9237,7 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
         try {
-          o.loop_->push_back(&o);
+          o.loop->push_back(&o);
         } catch(...) {
           set_error(std::move(REC(o)), current_exception());
         }
@@ -8747,13 +9380,13 @@ void run_loop::finish();
           using result_t = conditional_t<is_void_v<value_t>, unit, value_t>;
           struct awaitable-receiver;
 
-          variant<monostate, result_t, exception_ptr> result_{};
-          connect_result_t<Sndr, awaitable-receiver> state_;
+          variant<monostate, result_t, exception_ptr> result{};
+          connect_result_t<Sndr, awaitable-receiver> state;
 
          public:
           sender-awaitable(Sndr&& sndr, Promise& p);
           bool await_ready() const noexcept { return false; }
-          void await_suspend(coroutine_handle<Promise>) noexcept { start(state_); }
+          void await_suspend(coroutine_handle<Promise>) noexcept { start(state); }
           value_t await_resume();
         };
         
@@ -8763,8 +9396,8 @@ void run_loop::finish();
             struct awaitable-receiver {
               using receiver_concept = receiver_t;
-              variant<monostate, result_t, exception_ptr>* result_ptr_;
-              coroutine_handle<Promise> continuation_;
+              variant<monostate, result_t, exception_ptr>* result-ptr;
+              coroutine_handle<Promise> continuation;
               // ... see below
             };
             
@@ -8780,11 +9413,11 @@ void run_loop::finish();
                 try {
-                  rcvr.result_ptr_->emplace<1>(vs...);
+                  rcvr.result-ptr->emplace<1>(vs...);
                 } catch(...) {
-                  rcvr.result_ptr_->emplace<2>(current_exception());
+                  rcvr.result-ptr->emplace<2>(current_exception());
                 }
-                rcvr.continuation_.resume();
+                rcvr.continuation.resume();
                 
Otherwise, `set_value(rcvr, vs...)` is ill-formed. @@ -8792,26 +9425,26 @@ void run_loop::finish(); 2. The expression `set_error(rcvr, err)` is equivalent to:
-                rcvr.result_ptr_->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
-                rcvr.continuation_.resume();
+                rcvr.result-ptr->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
+                rcvr.continuation.resume();
                 
3. The expression `set_stopped(rcvr)` is equivalent to - static_cast<coroutine_handle<>>(rcvr.continuation_.promise().unhandled_stopped()).resume(). + static_cast<coroutine_handle<>>(rcvr.continuation.promise().unhandled_stopped()).resume(). 4. For any expression `tag` whose type satisfies forwarding-query and for any pack of subexpressions `as`, `get_env(crcvr).query(tag, as...)` is expression-equivalent to - tag(get_env(as_const(crcvr.continuation_.promise())), + tag(get_env(as_const(crcvr.continuation.promise())), as...) when that expression is well-formed. 2. sender-awaitable::sender-awaitable(Sndr&& sndr, Promise& p) - - Effects: initializes `state_` with + - Effects: initializes `state` with connect(std::forward<Sndr>(sndr), - awaitable-receiver{&result_, + awaitable-receiver{&result, coroutine_handle<Promise>::from_promise(p)}). 3. value_t sender-awaitable::await_resume() @@ -8819,10 +9452,10 @@ void run_loop::finish(); - Effects: equivalent to:
-                if (result_.index() == 2)
-                  rethrow_exception(get<2>(result_));
+                if (result.index() == 2)
+                  rethrow_exception(get<2>(result));
                 if constexpr (!is_void_v<value_t>)
-                  return std::forward<value_t>(get<1>(result_));
+                  return std::forward<value_t>(get<1>(result));
                 
2. `as_awaitable` is a customization point object. For some subexpressions @@ -8870,10 +9503,10 @@ void run_loop::finish(); requires (!same_as<OtherPromise, void>) void set_continuation(coroutine_handle<OtherPromise> h) noexcept; - coroutine_handle<> continuation() const noexcept { return continuation_; } + coroutine_handle<> continuation() const noexcept { return continuation; } coroutine_handle<> unhandled_stopped() noexcept { - return stopped_handler_(continuation_.address()); + return stopped-handler(continuation.address()); } template<class Value> @@ -8884,9 +9517,9 @@ void run_loop::finish(); [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept { terminate(); } - coroutine_handle<> continuation_{}; // exposition only + coroutine_handle<> continuation{}; // exposition only // exposition only - coroutine_handle<> (*stopped_handler_)(void*) noexcept = &default_unhandled_stopped; + coroutine_handle<> (*stopped-handler)(void*) noexcept = &default_unhandled_stopped; };
@@ -8895,14 +9528,14 @@ void run_loop::finish(); - Effects: equivalent to:
-      continuation_ = h;
+      continuation = h;
       if constexpr ( requires(OtherPromise& other) { other.unhandled_stopped(); } ) {
-        stopped_handler_ = [](void* p) noexcept -> coroutine_handle<> {
+        stopped-handler = [](void* p) noexcept -> coroutine_handle<> {
           return coroutine_handle<OtherPromise>::from_address(p)
             .promise().unhandled_stopped();
         };
       } else {
-        stopped_handler_ = default_unhandled_stopped;
+        stopped-handler = default_unhandled_stopped;
       }
       
@@ -8914,6 +9547,10 @@ void run_loop::finish(); return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));
+
+
+ +
 {
     "HPX": {

From 89e6eb60119945c4715370971cf6009317a38675 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Thu, 28 Mar 2024 20:04:44 -0700
Subject: [PATCH 45/89] more work on the stop token concepts, and respecifying
 stop_[token|source|callback]

---
 execution.bs | 421 +++++++++++++++++++++++++++++++++++----------------
 1 file changed, 288 insertions(+), 133 deletions(-)

diff --git a/execution.bs b/execution.bs
index 9c023f5..5f3433b 100644
--- a/execution.bs
+++ b/execution.bs
@@ -4105,18 +4105,19 @@ namespace std {
 
 2. stoppable_source,
     stoppable_token, and
-    stoppable_callback implementare
-    concepts that specify the required syntax and semantics of
-    shared ownershipaccess of a stop
-    state. Any stoppable_source,
+    stoppable_callback_for
+    implementare concepts that specify the required syntax
+    and semantics of shared ownershipaccess of a
+    stop state. Any
+    stoppable_source,
     stoppable_token, or
-    stoppable_callback that shares ownership
-    ofrefers to the same stop state is an associated stoppable_source,
+    stoppable_callback_for object that
+    shares ownership ofrefers to the same stop state is an
+    associated stoppable_source,
     stoppable_token, or
-    stoppable_callback, respectively. The last
-    remaining owner of the stop state automatically releases the resources
-    associated with the stop state.
+    stoppable_callback_for, respectively.
+    The last remaining owner of the stop state automatically releases the
+    resources associated with the stop state.
 
 3. A stoppable_token can be passed to an operation 
     whichthat can either
@@ -4134,8 +4135,9 @@ namespace std {
     stoppable_source objects. Once a stop request has
     been made it cannot be withdrawn (a subsequent stop request has no effect).
 
-4. Callbacks registered via a stoppable_callback object
-    are called when a stop request is first made by any associated
+4. Callbacks registered via a
+    stoppable_callback_for object are called
+    when a stop request is first made by any associated
     stoppable_source object.
 
 The following paragraph is moved to the specification of
@@ -4174,18 +4176,18 @@ declarations into the `` synopsis:
 
 
 namespace std {
-
// [thread.stoptoken.concepts], stop token concepts - template<class T> +
// [stoptoken.concepts], stop token concepts + template<class Callback, class Token, class Initializer = Callback> + concept stoppable_callback_for = see below; + + template<class Token> concept stoppable_token = see below; - template<class T> + template<class Token> concept unstoppable_token = see below; - template<class T> - concept stoppable_source = see below; - - template<class T> - concept stoppable_callback = see below;
+ template<class Source> + concept stoppable_source = see below;
// 33.3.3, class stop_token class stop_token; @@ -4212,11 +4214,11 @@ namespace std { class in_place_stop_source; // [stopcallback.inplace], class template in_place_stop_callback - template<class Fun> + template<class Callback> class in_place_stop_callback; - template<class T, class Fun> - using stop_callback_for_t = T::template callback_type<Fun>; + template<class T, class Callback> + using stop_callback_for_t = T::template callback_type<Callback>; }
@@ -4228,30 +4230,117 @@ Header `` synopsis [thread.stoptoken.syn] and Class
-### Stop token concepts [thread.stoptoken.concepts] ### {#spec-thread.stoptoken.concepts} +### Stop token concepts [stoptoken.concepts] ### {#spec-stoptoken.concepts} + +1. For a stop token type `Token` and a type `Callback` that is callable with no + arguments, if the type `stop_callback_for_t` is valid, it + denotes the type of a stop callback to use to register a callback to be + executed if a stop request is ever made on the `stoppable_token`'s + associated stop source. The `stoppable_callback_for` concept checks for a + callback compatible with a given stop token type. + +
+    template<class Callback, class Token, class Initializer = Callback>
+      concept stoppable_callback_for =
+        invocable<Callback> &&
+        constructible_from<Callback, Initializer> &&
+        requires { typename stop_callback_for_t<Token, Callback>; } &&
+        constructible_from<stop_callback_for_t<Token, Callback>, const Token&, Initializer>;
+    
+ +2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the + same logical shared stop state; let `init` be an object of type + `Initializer`; and let `CB` denote the type `stop_callback_for_t`. + +3. The concept `stoppable_callback_for` is modeled + only if: + + 1. The following concepts are modeled: + + * `constructible_from` + * `constructible_from` + * `constructible_from` + + 2. An object of type `CB` has an associated callback + function of type `Callback`. Let `cb` be an object of type `CB` + and let `callback` denote `cb`'s associated callback function. + Direct-non-list-initializing `cb` from arguments `t` and `init` shall + execute a stoppable callback registration as + follows: + + 1. If `t.stop_possible()` is `true`: + + 1. `callback` shall be direct-initialized with `init`. + + 2. Construction of `cb` shall only throw exceptions thrown by the + initialization of `callback` from `init`. + + 3. The callback invocation + std::forward<Callback>(callback)() shall + be registered with `t`'s associated stop state as follows: + + 1. If `t.stop_requested()` evaluates to `false` at the time of + registration, the callback invocation is added to the stop + state's list of callbacks such that + std::forward<Callback>(callback)() is + evaluated if a stop request is made on the stop state. + + 2. Otherwise, + std::forward<Callback>(callback)() + shall be immediately evaluated on the thread executing + `cb`'s constructor, and the callback invocation shall not be + added to the list of callback invocations. + + 4. If the callback invocation was added to stop state's list of + callbacks, `cb` shall be associated with the stop state. + + 2. If `t.stop_possible()` is `false`, there is no + requirement that the initialization of `cb` causes the + initialization of `callback`. + + 3. An evaluation of `u.stop_requested()` that strongly happens after + ([intro.races]/10) the beginning of the invocation of `callback` + shall return `true`. + + 4. Destruction of `cb` shall execute a stoppable callback + deregistration as follows: + + 1. If the constructor of `cb` did not register a callback invocation + with `t`'s stop state, then the stoppable callback + deregistration shall have no effect. -1. The `stoppable_token` concept checks for the basic interface of a stop token + 2. Otherwise, the invocation of `callback` shall be removed from + the shared stop state. + + 3. If `callback` is currently being invoked on another thread + then the stoppable callback deregistration shall block + ([defns.block]) until the invocation of `callback` returns + such that the return from the invocation of `callback` + strongly happens before ([intro.races]) the destruction of + `callback`. + + 4. If `callback` is executing on the current thread, then the + destructor shall not block waiting for the return from the + invocation of `callback`. + + 5. A stoppable callback deregistration shall not block on the completion + of the invocation of some other callback registered with the same + shared stop state. + + 6. As a final step, the stoppable callback deregistration shall destroy + the callback function. + + +4. The `stoppable_token` concept checks for the basic interface of a stop token that is copyable and allows polling to see if stop has been requested and - also whether a stop request is possible. For a stop token type `Token` and a - type `Fun` that is callable with no arguments, if the type - `stop_callback_for_t` is valid, it denotes the type of a stop - callback to use to register a callback to be executed if a stop request is - ever made on the `stoppable_token`'s associated stop source. The - exposition-only `stoppable-token-for` concept checks for a stop token - type compatible with a given callback type. The `unstoppable_token` concept + also whether a stop request is possible. The `unstoppable_token` concept checks for a stop token type that does not allow stopping.
     template<template<class> class>
       struct check-type-alias-exists; // exposition-only
 
-    template<class Token, class Fun, class Initializer = Fun>
-      concept stoppable-token-for = // exposition only
-        invocable<Fun> &&
-        constructible_from<Fun, Initializer> &&
-        requires { typename stop_callback_for_t<Token, Fun>; } &&
-        constructible_from<stop_callback_for_t<Token, Fun>, const Token&, Initializer>;
-
     template<class Token>
       concept stoppable_token =
         requires (const Token tok) {
@@ -4273,59 +4362,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class
         };
     
-2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the - same logical shared stop state; let `init` be an object of type `Initializer`; - let `Fun` be a type such that invocable<Fun> is `true`; and - let `CB` denote the type `stop_callback_for_t`. - -3. The exposition-only concept stoppable-token-for<Token, Fun, - Initializer> is modeled only if: - - 1. The following concepts are modeled: - - * `constructible_from` - * `constructible_from` - * `constructible_from` - - 2. Direct-non-list-initializing an object `cb` of type `CB` from arguments - `t` and `init` behaves as follows: - - 1. If `t.stop_possible()` is `false`, it is unspecified whether the - initialization of `cb` causes the construction of an instance of - type `Fun`. - - 2. Otherwise, if `t.stop_possible()` is `true`: - - 1. an instance `fun` of type `Fun` is direct-initialized with `init`, - and - - 2. `fun` is registered with `t`'s shared stop state such that `fun` - will be invoked with an empty argument list if a stop request is - made on the shared stop state. - - 3. If `t.stop_requested()` evaluates to `true` at the time `fun` is - registered then `fun` can be invoked on the thread executing - `cb`'s constructor. - - 4. Construction of `cb` shall only throw exceptions thrown by the - initialization of `fun` from `init`. - - 3. An evaluation of `u.stop_requested()` that strongly happens after - ([intro.races]/10) the beginning of the invocation of `fun` will return - `true`. - - 4. Destruction of `cb` removes `fun` from the shared stop state. - - 1. If `fun` is currently being invoked on another thread then the - destructor of `cb` will block until the invocation of `fun` returns - such that the return from the invocation of `fun` - strongly-happens-before the destruction of `fun`. - - 2. Destruction of a callback `cb` shall not block on the completion of - the invocation of some other callback registered with the same shared - stop state. - -4. The type `Token` models `stoppable_token` only if: +5. The type `Token` models `stoppable_token` only if: 1. If an evaluation, `E`, of `t.stop_possible()` evaluates to `false`, then evaluations of `u.stop_possible()` and `u.stop_requested()` that happen @@ -4335,10 +4372,10 @@ Header `` synopsis [thread.stoptoken.syn] and Class evaluations of `u.stop_possible()` and `u.stop_requested()` that happens after `E` shall evaluate to `true`. - 3. For any types `Fun` and `Initializer`, if `invocable && - constructible_from` is `true` and the type `CB` is - well-formed, then the concept stoppable-token-for<Token, - Fun, Initializer> shall be modeled. + 3. For any types `Callback` and `Initializer`, if + `stoppable_callback_for` is satisfied, + then `stoppable_callback_for` shall be + modeled. 4. A `stoppable_token` object has at most one associated logical stop state. A `stoppable_token` object with no associated stop state is said to be @@ -4347,7 +4384,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class `t` and `u` reference the same stop state, or if both `t` and `u` are disengaged, `t == u` shall be `true`; otherwise, it shall be `false`. -5. A model of `stoppable_source` can be queried whether stop has been requested +6. A model of `stoppable_source` can be queried whether stop has been requested (`stop_requested`) and whether stop is possible (`stop_possible`). It is a factory for associated stop tokens (`get_token`) and can be explicitly placed into the "stop requested" state (`request_stop`). It maintains a list @@ -4371,37 +4408,14 @@ Header `` synopsis [thread.stoptoken.syn] and Class to be disengaged. For a disengaged `stoppable_source` object, `stop_possible` and `stop_requested` shall return `false`. - 2. A stop token returned from `get_token()` is associated with the stop state - of the source. - - 3. The registration of a callback invocation either succeeds or fails. When - an invocation of a callback is registered, the following happens - atomically: - - - The stop state is checked. If stop has not been requested, the - callback invocation is added to the list of registered callback - invocations, and registration has succeeded. - - - Otherwise, registration has failed. + 2. A disengaged `stoppable_source` object shall return a disengaged stop token + from `get_token()`. Otherwise, `get_token()` shall return a stop token that + is associated with the stop state of the source. - 4. When an invocation of a callback is unregistered, the invocation is - atomically removed from the list of registered callback invocations. The - removal is not blocked by the concurrent execution of another callback - invocation in the list. If the callback invocation being unregistered is - currently executing, then: + The following paragraph is moved from the introduction, + with minor modifications (underlined in green). - - If the execution of the callback invocation is happening concurrently - on another thread, the completion of the execution strongly happens - before ([intro.races]) the end of the callback's lifetime. - - - Otherwise, the execution is happening on the current thread. Removal - of the callback invocation does not block waiting for the execution to - complete. - - The following paragraph is moved from the introduction, - with minor modifications (underlined in green). - - 5. Calls to the member functions `request_stop`, + 3. Calls to the member functions `request_stop`, `stop_requested`, and `stop_possible` and similarly named member functions on associated `stoppable_token` objects do not introduce data races. A call to `request_stop` that returns `true` synchronizes @@ -4411,6 +4425,29 @@ Header `` synopsis [thread.stoptoken.syn] and Class Registration of a callback synchronizes with the invocation of that callback. + The following paragraph is taken from + [[#spec-stopsource.mem]] and modified. + + 4. If the `stoppable_source` is disengaged, `request_stop` shall have no + effect and return `false`. Otherwise, it shall execute a stop request operation on the associated stop state. A + stop request operation determines whether the stop state has received a + stop request, and if not, makes a stop request. The determination and + making of the stop request shall happen atomically, as-if by a + read-modify-write operation ([intro.races]). If the request was made, + the stop state's registered callback invocations shall be synchronously + executed. If an invocation of a callback exits via an exception then + `terminate` shall be invoked ([except.terminate]). No constraint is placed on the order in which the + callback invocations are executed. `request_stop` shall return + `true` if a stop request was made, and `false` otherwise. After a call + to `request_stop` either `stop_possible()` shall be `false` or + `stop_requested()` shall be `true`. + + A stop request includes notifying all condition + variables of type `condition_variable_any` temporarily registered during an + interruptible wait ([thread.condvarany.intwait]). +
@@ -4731,11 +4768,17 @@ void swap(stop_source& rhs) noexcept; bool request_stop() noexcept;
-4. *Effects:* If `*this` does not have ownership of a stop - state`stop-state` is null, returns `false`. - Otherwise, atomically determines whether the owned stop state has received a - stop request, and if not, makes a stop request. The determination and making - of the stop request are an atomic read-modify-write operation +
+4. *Effects:* Executes a stop request operation ([stoptoken.concepts]) on the + associated stop state, if any. + +
+ +
+4. *Effects:* If `*this` does not have ownership of a stop state, returns + `false`. Otherwise, atomically determines whether the owned stop state has + received a stop request, and if not, makes a stop request. The determination + and making of the stop request are an atomic read-modify-write operation ([intro.races]). If the request was made, the callbacks registered by associated `stop_callback` objects are synchronously called. If an invocation of a callback exits via an exception then `terminate` is invoked @@ -4750,6 +4793,8 @@ bool request_stop() noexcept; 6. *Returns:* `true` if this call made a stop request; otherwise `false`. +
+
#### Non-member functions [stopsource.nonmembers] #### {#spec-stopsource.nonmembers} @@ -4770,10 +4815,120 @@ friend void swap(stop_source& x, stop_source& y) noexcept;
-
@@ -4864,12 +4864,10 @@ namespace std {
-3. *Remarks:* For a type `C`, if - stoppable_callback_for<Callback, stop_token, C> is - satisfied, then stoppable_callback_for< Callback, - stop_token, C> is modeled. The exposition-only `callback` member is - the associated callback function ([stoptoken.concepts]) of - `stop_callback` instances. +3. *Remarks:* For a type `C`, if `stoppable_callback_for` is satisfied, then `stoppable_callback_for` is + modeled. The exposition-only `callback` member is the associated callback + function ([stoptoken.concepts]) of `stop_callback` objects.
@@ -4991,11 +4989,8 @@ of Stop tokens [thread.stoptoken]. bool stop_possible() const noexcept; void swap(in_place_stop_token&) noexcept; - // [stoptoken.inplace.special], specialized algorithms - friend void swap(in_place_stop_token& lhs, in_place_stop_token& rhs) noexcept; - private: - const in_place_stop_source* stop-source = nullptr; // exposition only + const in_place_stop_source* stop-source = nullptr; // exposition only }; }
@@ -5032,14 +5027,6 @@ bool stop_possible() const noexcept; before the end of the storage duration of the associated `in_place_stop_source` object, if any. -#### Specialized algorithms [stoptoken.inplace.special] #### {#spec-stoptoken.inplace.special} - -
-friend void swap(in_place_stop_token& x, in_place_stop_token& y) noexcept;
-
- -2. *Effects*: Equivalent to: `x.swap(y);` - @@ -5052,14 +5039,11 @@ of Stop tokens [thread.stoptoken]. #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general} -1. The class `in_place_stop_source` implements the semantics of making a stop - request, without the need for a dynamic allocation of a shared state. A stop - request made on an `in_place_stop_source` object is visible to all - associated `in_place_stop_token` ([stoptoken.inplace]) objects. Once a stop - request has been made it cannot be withdrawn, and a subsequent stop request - has no effect. All uses of `in_place_stop_token` objects associated with a - given `in_place_stop_source` object shall happen before the start of the - destructor of that `in_place_stop_source` object. +1. The class `in_place_stop_source` models `stoppable_source`. Unlike + `stop_source`, `in_place_stop_source` does not require dynamic allocation or + reference counting of a shared stop state. Instead, it requires that all + uses of associated `in_place_stop_token` and `in_place_stop_callback` + objects happen before the `in_place_stop_source` is destroyed.
     namespace std {
@@ -5068,7 +5052,10 @@ of Stop tokens [thread.stoptoken].
         // [stopsource.inplace.cons], constructors, copy, and assignment
         in_place_stop_source() noexcept;
 
-        in_place_stop_source(in_place_stop_source&&) noexcept = delete;
+        in_place_stop_source(in_place_stop_source&&) = delete;
+        in_place_stop_source(const in_place_stop_source&) = delete;
+        in_place_stop_source& operator=(in_place_stop_source&&) = delete;
+        in_place_stop_source& operator=(const in_place_stop_source&) = delete;
         ~in_place_stop_source();
 
         //[stopsource.inplace.mem], stop handling
@@ -5080,33 +5067,6 @@ of Stop tokens [thread.stoptoken].
     }
     
- NOTE: find a way to share this wording with `stop_source`. maybe as a StopSource concept? - -2. An instance of `in_place_stop_source` maintains a list of registered callback - invocations. The registration of a callback invocation either succeeds or - fails. When an invocation of a callback is registered, the following happens - atomically: - - - The stop state is checked. If stop has not been requested, the callback - invocation is added to the list of registered callback invocations, - and registration has succeeded. - - - Otherwise, registration has failed. - - When an invocation of a callback is unregistered, the invocation is - atomically removed from the list of registered callback invocations. The - removal is not blocked by the concurrent execution of another callback - invocation in the list. If the callback invocation being unregistered is - currently executing, then: - - - If the execution of the callback invocation is happening concurrently on - another thread, the completion of the execution strongly happens - before ([intro.races]) the end of the callback's lifetime. - - - Otherwise, the execution is happening on the current thread. Removal of - the callback invocation does not block waiting for the execution to - complete. - #### Constructors, copy, and assignment [stopsource.inplace.cons] #### {#spec-stopsource.inplace.cons}
@@ -5136,18 +5096,10 @@ bool stop_requested() const noexcept;
 bool request_stop() noexcept;
 
-4. *Effects*: Atomically determines whether the stop state inside `*this` has - received a stop request, and if not, makes a stop request. The determination - and making of the stop request are an atomic read-modify-write operation - ([intro.races]). If the request was made, the registered invocations are - executed and the evaluations of the invocations are indeterminately - sequenced. If an invocation of a callback exits via an exception then - `terminate` is invoked ([except.terminate]). +4. *Effects*: Executes a stop request operation ([stoptoken.concepts]). 5. *Postconditions*: `stop_requested()` is `true`. -6. *Returns*: `true` if this call made a stop request; otherwise `false`. - @@ -5177,6 +5129,9 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. ~in_place_stop_callback(); in_place_stop_callback(in_place_stop_callback&&) = delete; + in_place_stop_callback(const in_place_stop_callback&) = delete; + in_place_stop_callback& operator=(in_place_stop_callback&&) = delete; + in_place_stop_callback& operator=(const in_place_stop_callback&) = delete; private: Callback stop-callback; // exposition only @@ -5188,22 +5143,21 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. }
-2. *Mandates*: `in_place_stop_callback` is instantiated with an argument for the +1. *Mandates*: `in_place_stop_callback` is instantiated with an argument for the template parameter `Callback` that satisfies both `invocable` and `destructible`. -3. *Preconditions*: `in_place_stop_callback` is instantiated with an argument - for the template parameter `Callback` that models both `invocable` and - `destructible`. - -REWORD: +2. *Remarks:* For a type `C`, if `stoppable_callback_for` is satisfied, then `stoppable_callback_for` is modeled. The exposition-only + `stop-callback` member is the associated callback function + ([stoptoken.concepts]) of `in_place_stop_callback` objects. -*Remarks:* Implementations are not permitted to ....<blah blah> (from optional) - - -4. *Recommended practice*: Implementations should use the storage of the - `in_place_stop_callback` objects to store the state necessary for their - association with an `in_place_stop_source` object. + Implementations are not permitted to use additional storage, such + as dynamic memory, to store the state necessary for an + `in_place_stop_callback`'s association with an `in_place_stop_source` object + or to register the callback invocation with the associated + `in_place_stop_source` object. #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons} @@ -5213,35 +5167,18 @@ template<class C> noexcept(is_nothrow_constructible_v<Callback, C>); -1. *Constraints*: `constructible_from` is modeled. - -SHARE THIS WORDING WITH STOP_TOKEN, MAYBE WITH A CONCEPT? +1. *Constraints*: `constructible_from` is satisfied. 2. *Effects*: Initializes stop-callback with - `std::forward(cb)`. Any `in_place_stop_source` associated with `st` - becomes associated with `*this`. Registers ([stopsource.inplace.general]) - the callback invocation - std::forward<Callback>(stop-callback)() with the - associated `in_place_stop_source`, if any. If the registration fails, - evaluates the callback invocation. - -3. *Throws*: Any exception thrown by the initialization of - stop-callback. - -4. *Remarks*: If evaluating - std::forward<Callback>(stop-callback)() exits via an - exception, then `terminate` is invoked ([except.terminate]). + `std::forward(cb)` and executes a stoppable callback registration + ([stoptoken.concepts]).
 ~in_place_stop_callback();
 
-6. *Effects*: Unregisters ([stopsource.inplace.general]) the callback invocation from - the associated `in_place_stop_source` object, if any. - -7. *Remarks*: A program has undefined behavior if the end of this destructor does - not strongly happen before the start of the destructor of the associated - `in_place_stop_source` object, if any. +6. *Effects*: Executes a stoppable callback deregistration + ([stoptoken.concepts]). From 51ae015547ca00d8776c0612f3b252033605c45b Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 29 Mar 2024 11:00:49 -0700 Subject: [PATCH 47/89] include namespaces in declarations --- execution.bs | 1878 ++++++++++++++++++++++++++------------------------ 1 file changed, 987 insertions(+), 891 deletions(-) diff --git a/execution.bs b/execution.bs index 246f388..2ecc471 100644 --- a/execution.bs +++ b/execution.bs @@ -1546,7 +1546,7 @@ The changes since R7 are as follows: Enhancements: - * The exposition-only class template basic-sender is greatly + * The exposition-only class template `basic-sender` is greatly enhanced, and the sender algorithms are respecified in term of it. * `enable_sender` and `enable_receiver` traits now have default @@ -1560,9 +1560,9 @@ The changes since R6 are as follows: Fixes: * Make it valid to pass non-variadic templates to the exposition-only alias - template gather-signatures, fixing the definitions of + template `gather-signatures`, fixing the definitions of `value_types_of_t`, `error_types_of_t`, and the exposition-only alias - template sync-wait-result-type. + template `sync-wait-result-type`. * Removed the query forwarding from `receiver_adaptor` that was inadvertantly left over from a previous edit. * When adapting a sender to an awaitable with `as_awaitable`, the sender's @@ -1582,7 +1582,7 @@ The changes since R6 are as follows: default implementations that look for nested `is_sender` and `is_receiver` types, respectively. * `get_attrs` is removed and `get_env` is used in its place. - * The exposition-only type empty-env is made normative + * The exposition-only type `empty-env` is made normative and is renamed `empty_env`. * `get_env` gets a fall-back implementation that simply returns `empty_env{}` if a `tag_invoke` overload is not found. @@ -1624,7 +1624,7 @@ The changes since R5 are as follows: * Make the specification of the alias templates `value_types_of_t` and `error_types_of_t`, and the variable template `sends_done` more concise by expressing them in terms of a new exposition-only alias template - gather-signatures. + `gather-signatures`. ### Environments and attributes ### {#environments-and-attributes} @@ -1918,7 +1918,7 @@ The changes since R2 are as follows: * Fix specification of the `on` algorithm to clarify lifetimes of intermediate operation states and properly scope the `get_scheduler` query. * Fix a memory safety bug in the implementation of - connect-awaitable. + `connect-awaitable`. * Fix recursive definition of the `scheduler` concept. Enhancements: @@ -2808,7 +2808,7 @@ nothing more than what is in this paper and the range support in C++20. A range of senders would allow you to model such input as keystrikes, mouse movements, sensor readings, or network requests. -Given some expression R that is a range of senders, consider +Given some expression `R` that is a range of senders, consider the following in a coroutine that returns an async generator type:
@@ -2820,17 +2820,17 @@ the following in a coroutine that returns an async generator type:
     }
     
-This transforms each element of the asynchronous sequence R +This transforms each element of the asynchronous sequence `R` with the function `fn` on demand, as the data arrives. The result is a new asynchronous sequence of the transformed values. -Now imagine that R is the simple expression `views::iota(0) +Now imagine that `R` is the simple expression `views::iota(0) | views::transform(execution::just)`. This creates a lazy range of senders, each of which completes immediately with monotonically increasing integers. The above code churns through the range, generating a new infine asynchronous range of values [`fn(0)`, `fn(1)`, `fn(2)`, ...]. -Far more interesting would be if R were a range of senders +Far more interesting would be if `R` were a range of senders representing, say, user actions in a UI. The above code gives a simple way to respond to user actions on demand. @@ -5001,7 +5001,7 @@ of Stop tokens [thread.stoptoken]. void swap(in_place_stop_token& rhs) noexcept; -1. *Effects*: Exchanges the values of stop-source and +1. *Effects*: Exchanges the values of `stop-source` and rhs.stop-source.
@@ -5169,7 +5169,7 @@ template<class C>
 
 1. *Constraints*: `constructible_from` is satisfied.
 
-2. *Effects*: Initializes stop-callback with
+2. *Effects*: Initializes `stop-callback` with
     `std::forward(cb)` and executes a stoppable callback registration
     ([stoptoken.concepts]).
 
@@ -5268,11 +5268,13 @@ template<class C>
             true.
 
     2. 
-        template<class T>
-          concept movable-value =
-            move_constructible<decay_t<T>> &&
-            constructible_from<decay_t<T>, T> &&
-            (!is_array_v<remove_cvref_t<T>>);
+        namespace std {
+          template<class T>
+            concept movable-value =
+              move_constructible<decay_t<T>> &&
+              constructible_from<decay_t<T>, T> &&
+              (!is_array_v<remove_cvref_t<T>>);
+        }
         
3. For function types `F1` and `F2` denoting `R1(Args1...)` and @@ -5306,7 +5308,7 @@ template<class C> and semantic requirements on its invocations. 2. Given a subexpression `env` that refers to a queryable object `o`, a query - object q, and a (possibly empty) pack of subexpressions + object `q`, and a (possibly empty) pack of subexpressions `args`, the expression q(env, args...) is equal to ([concepts.equality]) the expression q(c, args...) where `c` is a `const` lvalue reference to `o`. @@ -5326,18 +5328,20 @@ template<class C> ### `queryable` concept [exec.queryable.concept] ### {#spec-execution.queryable.concept}
-    template<class T>
-      concept queryable = destructible<T>;
+    namespace std {
+      template<class T>
+        concept queryable = destructible<T>;
+    }
     
1. The `queryable` concept specifies the constraints on the types of queryable objects. 2. Let `env` be an object of type `Env`. The type `Env` models `queryable` if - for each callable object q and a pack of subexpressions + for each callable object `q` and a pack of subexpressions `args`, if requires { q(env, args...) } is `true` then q(env, args...) meets any semantic requirements imposed - by q. + by `q`. ## Asynchronous operations [async.ops] ## {#spec-execution-async.ops} @@ -5488,8 +5492,8 @@ template<class C> describes a completion operation. An asychronous operation has a finite set of possible completion signatures corresponding to the completion operations that the asynchronous operation potentially evaluates ([basic.def.odr]). For - a completion function set, receiver - rcvr, and pack of arguments args, + a completion function `set`, receiver + `rcvr`, and pack of arguments `args`, let `c` be the completion operation set(rcvr, args...), and let `F` be the function type decltype(auto(set))(decltype((args))...). @@ -5830,9 +5834,11 @@ namespace std::execution { exposition-only class type:
-        struct empty-variant {
-          empty-variant() = delete;
-        };
+        namespace std::execution {
+          struct empty-variant {
+            empty-variant() = delete;
+          };
+        }
         
## Queries [exec.queries] ## {#spec-execution.queries} @@ -5966,11 +5972,13 @@ namespace std::execution { ### `execution::get_forward_progress_guarantee` [exec.get.forward.progress.guarantee] ### {#spec-execution.get_forward_progress_guarantee}
-enum class forward_progress_guarantee {
-  concurrent,
-  parallel,
-  weakly_parallel
-};
+namespace std::execution {
+  enum class forward_progress_guarantee {
+    concurrent,
+    parallel,
+    weakly_parallel
+  };
+}
 
1. `get_forward_progress_guarantee` asks a scheduler about the forward progress @@ -6055,24 +6063,26 @@ enum class forward_progress_guarantee { scheduler. A valid invocation of `schedule` is a schedule-expression.
-    template<class Sch>
-      concept enable-scheduler = // exposition only
-        requires {
-          requires derived_from<typename Sch::scheduler_concept, scheduler_t>;
-        };
+    namespace std::execution {
+      template<class Sch>
+        concept enable-scheduler = // exposition only
+          requires {
+            requires derived_from<typename Sch::scheduler_concept, scheduler_t>;
+          };
 
-    template<class Sch>
-      concept scheduler =
-        enable-scheduler<remove_cvref_t<Sch>> &&
-        queryable<Sch> &&
-        requires(Sch&& sch) {
-          { schedule(std::forward<Sch>(sch)) } -> sender;
-          { get_completion_scheduler<set_value_t>(
-              get_env(schedule(std::forward<Sch>(sch)))) }
-                -> same_as<remove_cvref_t<Sch>>;
-        } &&
-        equality_comparable<remove_cvref_t<Sch>> &&
-        copy_constructible<remove_cvref_t<Sch>>;
+      template<class Sch>
+        concept scheduler =
+          enable-scheduler<remove_cvref_t<Sch>> &&
+          queryable<Sch> &&
+          requires(Sch&& sch) {
+            { schedule(std::forward<Sch>(sch)) } -> sender;
+            { get_completion_scheduler<set_value_t>(
+                get_env(schedule(std::forward<Sch>(sch)))) }
+                  -> same_as<remove_cvref_t<Sch>>;
+          } &&
+          equality_comparable<remove_cvref_t<Sch>> &&
+          copy_constructible<remove_cvref_t<Sch>>;
+    }
     
2. Let `Sch` be the type of a scheduler and let `Env` be the type of an execution @@ -6116,39 +6126,41 @@ enum class forward_progress_guarantee { customization point is used to access a receiver's associated environment.
-    template<class Rcvr>
-      concept enable-receiver = // exposition only
-        requires {
-          requires derived_from<typename Rcvr::receiver_concept, receiver_t>;
-        };
+    namespace std::execution {
+      template<class Rcvr>
+        concept enable-receiver = // exposition only
+          requires {
+            requires derived_from<typename Rcvr::receiver_concept, receiver_t>;
+          };
 
-    template<class Rcvr>
-      concept receiver =
-        enable-receiver<remove_cvref_t<Rcvr>> &&
-        requires(const remove_cvref_t<Rcvr>& rcvr) {
-          { get_env(rcvr) } -> queryable;
-        } &&
-        move_constructible<remove_cvref_t<Rcvr>> &&  // rvalues are movable, and
-        constructible_from<remove_cvref_t<Rcvr>, Rcvr>; // lvalues are copyable
-
-    template<class Signature, class Rcvr>
-      concept valid-completion-for = // exposition only
-        requires (Signature* sig) {
-          []<class Tag, class... Args>(Tag(*)(Args...))
-              requires callable<Tag, remove_cvref_t<Rcvr>, Args...>
-          {}(sig);
-        };
+      template<class Rcvr>
+        concept receiver =
+          enable-receiver<remove_cvref_t<Rcvr>> &&
+          requires(const remove_cvref_t<Rcvr>& rcvr) {
+            { get_env(rcvr) } -> queryable;
+          } &&
+          move_constructible<remove_cvref_t<Rcvr>> &&  // rvalues are movable, and
+          constructible_from<remove_cvref_t<Rcvr>, Rcvr>; // lvalues are copyable
+
+      template<class Signature, class Rcvr>
+        concept valid-completion-for = // exposition only
+          requires (Signature* sig) {
+            []<class Tag, class... Args>(Tag(*)(Args...))
+                requires callable<Tag, remove_cvref_t<Rcvr>, Args...>
+            {}(sig);
+          };
 
-    template<class Rcvr, class Completions>
-      concept has-completions = // exposition only
-        requires (Completions* completions) {
-          []<valid-completion-for<Rcvr>...Sigs>(completion_signatures<Sigs...>*)
-          {}(completions);
-        };
+      template<class Rcvr, class Completions>
+        concept has-completions = // exposition only
+          requires (Completions* completions) {
+            []<valid-completion-for<Rcvr>...Sigs>(completion_signatures<Sigs...>*)
+            {}(completions);
+          };
 
-    template<class Rcvr, class Completions>
-      concept receiver_of =
-        receiver<Rcvr> && has-completions<Rcvr, Completions>;
+      template<class Rcvr, class Completions>
+        concept receiver_of =
+          receiver<Rcvr> && has-completions<Rcvr, Completions>;
+    }
     
2. Class types that are `final` do not model the `receiver` concept. @@ -6191,20 +6203,22 @@ enum class forward_progress_guarantee { type ([async.ops]).
-    template<class Rcvr>
-      concept enable-opstate = // exposition only
-        requires {
-          requires derived_from<typename Rcvr::operation_state_concept, operation_state_t>;
-        };
+    namespace std::execution {
+      template<class Rcvr>
+        concept enable-opstate = // exposition only
+          requires {
+            requires derived_from<typename Rcvr::operation_state_concept, operation_state_t>;
+          };
 
-    template<class O>
-      concept operation_state =
-        enable-opstate<remove_cvref_t<O>> &&
-        queryable<O> &&
-        is_object_v<O> &&
-        requires (O& o) {
-          { start(o) } noexcept;
-        };
+      template<class O>
+        concept operation_state =
+          enable-opstate<remove_cvref_t<O>> &&
+          queryable<O> &&
+          is_object_v<O> &&
+          requires (O& o) {
+            { start(o) } noexcept;
+          };
+    }
     
2. If an `operation_state` object is moved during the lifetime of its @@ -6340,11 +6354,11 @@ enum class forward_progress_guarantee { Tag, const Env& env, Default&& value) noexcept(see below);
- 1. Let e be the expression `Tag()(env)` if that + 1. Let `e` be the expression `Tag()(env)` if that expression is well-formed; otherwise, it is `static_cast(std::forward(value))`. - 2. Returns: e. + 2. Returns: `e`. 3. Remarks: The expression in the `noexcept` clause is noexcept(e). @@ -6444,7 +6458,7 @@ enum class forward_progress_guarantee { 1. An expression of type - product-type is usable as the initializer of a + `product-type` is usable as the initializer of a structured binding declaration [dcl.struct.bind]. 14.
@@ -6454,173 +6468,175 @@ enum class forward_progress_guarantee {
 
         1. *Returns:* A prvalue of type basic-sender<Tag,
             decay_t<Data>, decay_t<Child>...> where the
-            tag member has been default-initialized and the
-            data and
+            `tag` member has been default-initialized and the
+            `data` and
             childn... members have been direct
             initialized from their respective forwarded arguments, where
-            basic-sender is the following exposition-only
+            `basic-sender` is the following exposition-only
             class template except as noted below:
 
               
-              template<class T, class... Us>
-              concept one-of = (same_as<T, Us> ||...); // exposition only
+              namespace std::execution {
+                template<class T, class... Us>
+                concept one-of = (same_as<T, Us> ||...); // exposition only
 
-              template<class Tag>
-              concept completion-tag = // exposition only
-                one-of<Tag, set_value_t, set_error_t, set_stopped_t>;
+                template<class Tag>
+                concept completion-tag = // exposition only
+                  one-of<Tag, set_value_t, set_error_t, set_stopped_t>;
 
-              template<template<class...> class T, class... Args>
-              concept well-formed = requires { typename T<Args...>; }; // exposition only
+                template<template<class...> class T, class... Args>
+                concept well-formed = requires { typename T<Args...>; }; // exposition only
 
-              template<const auto& Fun, class... Args>
-              concept cpo-callable = callable<decltype(Fun), Args...>; // exposition only
+                template<const auto& Fun, class... Args>
+                concept cpo-callable = callable<decltype(Fun), Args...>; // exposition only
 
-              template<const auto& Fun, class... Args>
-              using cpo-result-t = call-result-t<decltype(Fun), Args...>; // exposition only
+                template<const auto& Fun, class... Args>
+                using cpo-result-t = call-result-t<decltype(Fun), Args...>; // exposition only
 
-              struct default-impls {  // exposition only
-                static constexpr auto get-attrs = see below;
-                static constexpr auto get-env = see below;
-                static constexpr auto get-state = see below;
-                static constexpr auto start = see below;
-                static constexpr auto complete = see below;
-              };
+                struct default-impls {  // exposition only
+                  static constexpr auto get-attrs = see below;
+                  static constexpr auto get-env = see below;
+                  static constexpr auto get-state = see below;
+                  static constexpr auto start = see below;
+                  static constexpr auto complete = see below;
+                };
 
-              template<class Tag>
-              struct impls-for : default-impls {}; // exposition only
-
-              template<class Sndr, class Rcvr> // exposition only
-              using state-type = decay_t<cpo-result-t<
-                impls-for<tag_of_t<Sndr>>::get-state, Sndr, Rcvr&>>;
-
-              template<class Index, class Sndr, class Rcvr> // exposition only
-              using env-type = cpo-result-t<
-                impls-for<tag_of_t<Sndr>>::get-env, Index,
-                state-type<Sndr, Rcvr>&, const Rcvr&>>;
-
-              template<class Sndr, class Rcvr, class Index> 
-                requires well-formed<env-type, Index, Sndr, Rcvr>
-              struct basic-receiver {  // exposition only
-                using tag-type = tag_of_t<Sndr>; // exposition only
-                using receiver_concept = receiver_t;
-
-                template<class... Args>
-                  requires cpo-callable<impls-for<tag-type>::complete,
-                    Index, state-type<Sndr, Rcvr>&, Rcvr&, set_value_t, Args...>
-                void set_value(Args&&... args) && noexcept {
-                  (void) impls-for<tag-type>::complete(
-                    Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...);
-                }
+                template<class Tag>
+                struct impls-for : default-impls {}; // exposition only
 
-                template<class Error>
-                  requires cpo-callable<impls-for<tag-type>::complete,
-                    Index, state-type<Sndr, Rcvr>&, Rcvr&, set_error_t, Error>
-                void set_error(Error&& err) && noexcept {
-                  (void) impls-for<tag-type>::complete(
-                    Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err));
-                }
+                template<class Sndr, class Rcvr> // exposition only
+                using state-type = decay_t<cpo-result-t<
+                  impls-for<tag_of_t<Sndr>>::get-state, Sndr, Rcvr&>>;
 
-                void set_stopped() && noexcept
-                  requires cpo-callable<impls-for<tag-type>::complete,
-                    Index, state-type<Sndr, Rcvr>&, Rcvr&, set_stopped_t> {
-                  (void) impls-for<tag-type>::complete(
-                    Index(), op->state, op->rcvr, set_stopped_t());
-                }
+                template<class Index, class Sndr, class Rcvr> // exposition only
+                using env-type = cpo-result-t<
+                  impls-for<tag_of_t<Sndr>>::get-env, Index,
+                  state-type<Sndr, Rcvr>&, const Rcvr&>>;
 
-                auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> {
-                  const auto& rcvr = op->rcvr;
-                  return impls-for<tag-type>::get-env(Index(), op->state, rcvr);
-                }
+                template<class Sndr, class Rcvr, class Index> 
+                  requires well-formed<env-type, Index, Sndr, Rcvr>
+                struct basic-receiver {  // exposition only
+                  using tag-type = tag_of_t<Sndr>; // exposition only
+                  using receiver_concept = receiver_t;
 
-                basic-operation<Sndr, Rcvr>* op; // exposition only
-              };
+                  template<class... Args>
+                    requires cpo-callable<impls-for<tag-type>::complete,
+                      Index, state-type<Sndr, Rcvr>&, Rcvr&, set_value_t, Args...>
+                  void set_value(Args&&... args) && noexcept {
+                    (void) impls-for<tag-type>::complete(
+                      Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...);
+                  }
 
-              constexpr auto connect-all =   // exposition only
-                []<class Sndr, class Rcvr, size_t... Is>(
-                  basic-operation<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>)
-                    noexcept( TODO ) requires ( TODO ) {
-                    auto&& [ign1, ign2, ...child] = std::forward<Sndr>(sndr);
-                    return product-type{connect(
-                      std::forward_like<Sndr>(child),
-                      basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
-                  };
+                  template<class Error>
+                    requires cpo-callable<impls-for<tag-type>::complete,
+                      Index, state-type<Sndr, Rcvr>&, Rcvr&, set_error_t, Error>
+                  void set_error(Error&& err) && noexcept {
+                    (void) impls-for<tag-type>::complete(
+                      Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err));
+                  }
 
-              template<class Sndr>
-              using indices-for = make_index_sequence<tuple_size_v<Sndr>-2>; // exposition only
-
-              template<class Sndr, class Rcvr>
-              using inner-ops-tuple =   // exposition only
-                cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr,
-                  indices-for<Sndr>>;
-
-              template<class Sndr, class Rcvr>
-                requires well-formed<state-type, Sndr, Rcvr> &&
-                  well-formed<inner-ops-tuple, Sndr, Rcvr>
-              struct basic-operation {  // exposition only
-                using operation_state_concept = operation_state_t;
-                using tag-type = tag_of_t<Sndr>; // exposition only
-
-                Rcvr rcvr; // exposition only
-                state-type<Sndr, Rcvr> state; // exposition only
-                inner-ops-tuple<Sndr, Rcvr> inner-ops; // exposition only
-
-                basic-operation(Sndr&& sndr, Rcvr rcvr_init)  // exposition only
-                  : rcvr(std::move(rcvr_init))
-                  , state(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr))
-                  , inner-ops(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
-                {}
-
-                void start() & noexcept {
-                  auto& [...ops] = inner-ops;
-                  impls-for<tag-type>::start(state, rcvr, ops...);
-                }
-              };
+                  void set_stopped() && noexcept
+                    requires cpo-callable<impls-for<tag-type>::complete,
+                      Index, state-type<Sndr, Rcvr>&, Rcvr&, set_stopped_t> {
+                    (void) impls-for<tag-type>::complete(
+                      Index(), op->state, op->rcvr, set_stopped_t());
+                  }
 
-              template<class Sndr, class Env>
-              using completion-signatures-for =  see below; // exposition only
+                  auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> {
+                    const auto& rcvr = op->rcvr;
+                    return impls-for<tag-type>::get-env(Index(), op->state, rcvr);
+                  }
 
-              template<class Tag, class Data, class... Child>
-              struct basic-sender {  // exposition only
-                using sender_concept = sender_t;
+                  basic-operation<Sndr, Rcvr>* op; // exposition only
+                };
 
-                decltype(auto) get_env() const noexcept {
-                  return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
-                }
+                constexpr auto connect-all =   // exposition only
+                  []<class Sndr, class Rcvr, size_t... Is>(
+                    basic-operation<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>)
+                      noexcept( TODO ) requires ( TODO ) {
+                      auto&& [ign1, ign2, ...child] = std::forward<Sndr>(sndr);
+                      return product-type{connect(
+                        std::forward_like<Sndr>(child),
+                        basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
+                    };
+
+                template<class Sndr>
+                using indices-for = make_index_sequence<tuple_size_v<Sndr>-2>; // exposition only
+
+                template<class Sndr, class Rcvr>
+                using inner-ops-tuple =   // exposition only
+                  cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr,
+                    indices-for<Sndr>>;
+
+                template<class Sndr, class Rcvr>
+                  requires well-formed<state-type, Sndr, Rcvr> &&
+                    well-formed<inner-ops-tuple, Sndr, Rcvr>
+                struct basic-operation {  // exposition only
+                  using operation_state_concept = operation_state_t;
+                  using tag-type = tag_of_t<Sndr>; // exposition only
+
+                  Rcvr rcvr; // exposition only
+                  state-type<Sndr, Rcvr> state; // exposition only
+                  inner-ops-tuple<Sndr, Rcvr> inner-ops; // exposition only
+
+                  basic-operation(Sndr&& sndr, Rcvr rcvr_init)  // exposition only
+                    : rcvr(std::move(rcvr_init))
+                    , state(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr))
+                    , inner-ops(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
+                  {}
+
+                  void start() & noexcept {
+                    auto& [...ops] = inner-ops;
+                    impls-for<tag-type>::start(state, rcvr, ops...);
+                  }
+                };
 
-                template<decays-to<basic-sender> Self, receiver Rcvr>
-                auto connect(this Self&& self, Rcvr rcvr) -> basic-operation<Self, Rcvr> {
-                  return {std::forward<Self>(self), std::move(rcvr)};
-                }
+                template<class Sndr, class Env>
+                using completion-signatures-for =  see below; // exposition only
 
-                template<decays-to<basic-sender> Self, class Env>
-                auto get_completion_signatures(this Self&& self, Env&& env) noexcept
-                  -> completion-signatures-for<Self, Env> {
-                  return {};
-                }
+                template<class Tag, class Data, class... Child>
+                struct basic-sender {  // exposition only
+                  using sender_concept = sender_t;
 
-                Tag tag;            // exposition only
-                Data data;          // exposition only
-                Child0 child0;      // exposition only
-                Child1 child1;      // exposition only
-                  ...
-                Childn-1 childn-1;   // exposition only
-              };
+                  decltype(auto) get_env() const noexcept {
+                    return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
+                  }
 
-              template <class Sndr>
-              using data-type = decltype((declval<Sndr>().data)); // exposition only
+                  template<decays-to<basic-sender> Self, receiver Rcvr>
+                  auto connect(this Self&& self, Rcvr rcvr) -> basic-operation<Self, Rcvr> {
+                    return {std::forward<Self>(self), std::move(rcvr)};
+                  }
+
+                  template<decays-to<basic-sender> Self, class Env>
+                  auto get_completion_signatures(this Self&& self, Env&& env) noexcept
+                    -> completion-signatures-for<Self, Env> {
+                    return {};
+                  }
+
+                  Tag tag;            // exposition only
+                  Data data;          // exposition only
+                  Child0 child0;      // exposition only
+                  Child1 child1;      // exposition only
+                    ...
+                  Childn-1 childn-1;   // exposition only
+                };
 
-              template <class Sndr, size_t N = 0>
-              using child-type = decltype((declval<Sndr>().childN)); // exposition only
+                template <class Sndr>
+                using data-type = decltype((declval<Sndr>().data)); // exposition only
+
+                template <class Sndr, size_t N = 0>
+                using child-type = decltype((declval<Sndr>().childN)); // exposition only
+              }
               
2. *Remarks:* The default template argument for the `Data` template parameter denotes an unspecified empty trivial class type. - 3. It is unspecified whether instances of basic-sender can be + 3. It is unspecified whether instances of `basic-sender` can be aggregate initialized. 4. An expression of type - basic-sender is usable as the initializer of a + `basic-sender` is usable as the initializer of a structured binding declaration [dcl.struct.bind]. 5. The member default-impls::get-attrs is @@ -6705,45 +6721,47 @@ enum class forward_progress_guarantee { sender and a receiver to produce an operation state.
-    template<class Sigs>
-      concept valid-completion-signatures = see below; // exposition only
-
-    template<class Sndr>
-      concept is-sender = // exposition only
-        requires {
-          requires derived_from<typename Sndr::sender_concept, sender_t>;
-        };
-
-    template<class Sndr>
-      concept enable-sender = // exposition only
-        is-sender<Sndr> ||
-        is-awaitable<Sndr, env-promise<empty_env>>;  // [exec.awaitables]
-
-    template<class Sndr>
-      concept sender =
-        bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint
-        requires (const remove_cvref_t<Sndr>& sndr) {
-          { get_env(sndr) } -> queryable;
-        } &&
-        move_constructible<remove_cvref_t<Sndr>> &&  // rvalues are movable, and
-        constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable
+    namespace std::execution {
+      template<class Sigs>
+        concept valid-completion-signatures = see below; // exposition only
+
+      template<class Sndr>
+        concept is-sender = // exposition only
+          requires {
+            requires derived_from<typename Sndr::sender_concept, sender_t>;
+          };
 
-    template<class Sndr, class Env = empty_env>
-      concept sender_in =
-        sender<Sndr> &&
-        queryable<Env> &&
-        requires (Sndr&& sndr, Env&& env) {
-          { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) }
-            -> valid-completion-signatures;
-        };
+      template<class Sndr>
+        concept enable-sender = // exposition only
+          is-sender<Sndr> ||
+          is-awaitable<Sndr, env-promise<empty_env>>;  // [exec.awaitables]
+
+      template<class Sndr>
+        concept sender =
+          bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint
+          requires (const remove_cvref_t<Sndr>& sndr) {
+            { get_env(sndr) } -> queryable;
+          } &&
+          move_constructible<remove_cvref_t<Sndr>> &&  // rvalues are movable, and
+          constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable
+
+      template<class Sndr, class Env = empty_env>
+        concept sender_in =
+          sender<Sndr> &&
+          queryable<Env> &&
+          requires (Sndr&& sndr, Env&& env) {
+            { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) }
+              -> valid-completion-signatures;
+          };
 
-    template<class Sndr, class Rcvr>
-      concept sender_to =
-        sender_in<Sndr, env_of_t<Rcvr>> &&
-        receiver_of<Rcvr, completion_signatures_of_t<Sndr, env_of_t<Rcvr>>> &&
-        requires (Sndr&& sndr, Rcvr&& rcvr) {
-          connect(std::forward<Sndr>(sndr), std::forward<Rcvr>(rcvr));
-        };
+      template<class Sndr, class Rcvr>
+        concept sender_to =
+          sender_in<Sndr, env_of_t<Rcvr>> &&
+          receiver_of<Rcvr, completion_signatures_of_t<Sndr, env_of_t<Rcvr>>> &&
+          requires (Sndr&& sndr, Rcvr&& rcvr) {
+            connect(std::forward<Sndr>(sndr), std::forward<Rcvr>(rcvr));
+          };
+    }
     
2. Given a subexpression `sndr`, let `Sndr` be `decltype((sndr))`, let `Env` be @@ -6758,26 +6776,28 @@ enum class forward_progress_guarantee { `Sndr` and `Env`. 3. A type `Sigs` satisfies and models the exposition-only concept - valid-completion-signatures if it denotes a specialization + `valid-completion-signatures` if it denotes a specialization of the `completion_signatures` class template. -4. The exposition-only concepts sender-of and - sender-of-in define the requirements for a sender +4. The exposition-only concepts `sender-of` and + `sender-of-in` define the requirements for a sender type that completes with a given unique set of value result types.
-    template<class... As>
-      using value-signature = set_value_t(As...); // exposition only
-
-    template<class Sndr, class Env, class... Values>
-      concept sender-of-in =
-        sender_in<Sndr, Env> &&
-        MATCHING-SIG( // see [exec.general]
-          set_value_t(Values...),
-          value_types_of_t<Sndr, Env, value-signature, type_identity_t>);
-
-    template<class Sndr, class... Values>
-      concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
+    namespace std::execution {
+      template<class... As>
+        using value-signature = set_value_t(As...); // exposition only
+
+      template<class Sndr, class Env, class... Values>
+        concept sender-of-in =
+          sender_in<Sndr, Env> &&
+          MATCHING-SIG( // see [exec.general]
+            set_value_t(Values...),
+            value_types_of_t<Sndr, Env, value-signature, type_identity_t>);
+
+      template<class Sndr, class... Values>
+        concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
+    }
     
5. Let `sndr` be an expression such that `decltype((sndr))` is `Sndr`. The type @@ -6795,13 +6815,15 @@ enum class forward_progress_guarantee { makes it possible to implement this purely in the library. P2141 has already been approved by EWG for C++26. -6. Let sender-for be an exposition-only concept defined as follows: +6. Let `sender-for` be an exposition-only concept defined as follows:
-    template<class Sndr, class Tag>
-    concept sender-for =
-      sender<Sndr> &&
-      same_as<tag_of_t<Sndr>, Tag>;
+    namespace std::execution {
+      template<class Sndr, class Tag>
+      concept sender-for =
+        sender<Sndr> &&
+        same_as<tag_of_t<Sndr>, Tag>;
+    }
     
7. For a type `T`, SET-VALUE-SIG(T) denotes the type @@ -6839,26 +6861,28 @@ enum class forward_progress_guarantee { [cwg#250](https://github.com/cplusplus/CWG/issues/250) to give these transformations a term-of-art so we can more easily refer to it here. -3. Let is-awaitable be the following exposition-only +3. Let `is-awaitable` be the following exposition-only concept:
-    template<class T>
-    concept await-suspend-result = see below;
-
-    template<class A, class Promise>
-    concept is-awaiter = // exposition only
-      requires (A& a, coroutine_handle<Promise> h) {
-        a.await_ready() ? 1 : 0;
-        { a.await_suspend(h) } -> await-suspend-result;
-        a.await_resume();
-      };
+    namespace std {
+      template<class T>
+      concept await-suspend-result = see below;
+
+      template<class A, class Promise>
+      concept is-awaiter = // exposition only
+        requires (A& a, coroutine_handle<Promise> h) {
+          a.await_ready() ? 1 : 0;
+          { a.await_suspend(h) } -> await-suspend-result;
+          a.await_resume();
+        };
 
-    template<class C, class Promise>
-    concept is-awaitable =
-      requires (C (*fc)() noexcept, Promise& p) {
-        { GET-AWAITER(fc(), p) } -> is-awaiter<Promise>;
-      };
+      template<class C, class Promise>
+      concept is-awaitable =
+        requires (C (*fc)() noexcept, Promise& p) {
+          { GET-AWAITER(fc(), p) } -> is-awaiter<Promise>;
+        };
+    }
     
await-suspend-result<T> is `true` if and only if one @@ -6872,67 +6896,73 @@ enum class forward_progress_guarantee { an lvalue `p` of type `Promise`, await-result-type<C, Promise> denotes the type decltype(GET-AWAITER(c, p).await_resume()). -5. Let with-await-transform be the exposition-only class template: +5. Let `with-await-transform` be the exposition-only class template:
-    template<class T, class Promise>
-      concept has-as-awaitable = // exposition only
-        requires (T&& t, Promise& p) {
-          { std::forward<T>(t).as_awaitable(p) } -> is-awaitable<Promise&>;
-        };
+    namespace std::execution {
+      template<class T, class Promise>
+        concept has-as-awaitable = // exposition only
+          requires (T&& t, Promise& p) {
+            { std::forward<T>(t).as_awaitable(p) } -> is-awaitable<Promise&>;
+          };
 
-    template<class Derived>
-      struct with-await-transform {
-        template<class T>
-          T&& await_transform(T&& value) noexcept {
-            return std::forward<T>(value);
-          }
+      template<class Derived>
+        struct with-await-transform {
+          template<class T>
+            T&& await_transform(T&& value) noexcept {
+              return std::forward<T>(value);
+            }
 
-        template<has-as-awaitable<Derived> T>
-          auto await_transform(T&& value)
-            noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>())))
-            -> decltype(std::forward<T>(value).as_awaitable(declval<Derived&>())) {
-            return std::forward<T>(value).as_awaitable(static_cast<Derived&>(*this));
-          }
-      };
+          template<has-as-awaitable<Derived> T>
+            auto await_transform(T&& value)
+              noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>())))
+              -> decltype(std::forward<T>(value).as_awaitable(declval<Derived&>())) {
+              return std::forward<T>(value).as_awaitable(static_cast<Derived&>(*this));
+            }
+        };
+    }
     
-6. Let env-promise be the exposition-only class template: +6. Let `env-promise` be the exposition-only class template:
-    template<class Env>
-    struct env-promise : with-await-transform<env-promise<Env>> {
-      unspecified get_return_object() noexcept;
-      unspecified initial_suspend() noexcept;
-      unspecified final_suspend() noexcept;
-      void unhandled_exception() noexcept;
-      void return_void() noexcept;
-      coroutine_handle<> unhandled_stopped() noexcept;
-
-      const Env& get_env() const noexcept;
-    };
+    namespace std::execution {
+      template<class Env>
+      struct env-promise : with-await-transform<env-promise<Env>> {
+        unspecified get_return_object() noexcept;
+        unspecified initial_suspend() noexcept;
+        unspecified final_suspend() noexcept;
+        void unhandled_exception() noexcept;
+        void return_void() noexcept;
+        coroutine_handle<> unhandled_stopped() noexcept;
+
+        const Env& get_env() const noexcept;
+      };
+    }
     
- Specializations of env-promise + Specializations of `env-promise` are only used for the purpose of type computation; its members need not be defined. ### `execution::default_domain` [exec.domain.default] ### {#spec-execution.default_domain}
-struct default_domain {
-  template <sender Sndr, queryable... Env>
-      requires (sizeof...(Env) <= 1)
-    static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
-      noexcept(see below);
-
-  template <sender Sndr, queryable Env>
-    static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
-
-  template<class Tag, sender Sndr, class... Args>
-    static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
-      noexcept(see below);
-};
+namespace std::execution {
+  struct default_domain {
+    template <sender Sndr, queryable... Env>
+        requires (sizeof...(Env) <= 1)
+      static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
+        noexcept(see below);
+
+    template <sender Sndr, queryable Env>
+      static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+
+    template<class Tag, sender Sndr, class... Args>
+      static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
+        noexcept(see below);
+  };
+}
 
#### Static members [exec.domain.default.statics] #### {#spec-execution.default_domain.statics} @@ -6944,11 +6974,11 @@ template <sender Sndr, queryable... Env> noexcept(see below);
-1. Let e be the expression +1. Let `e` be the expression `tag_of_t().transform_sender(std::forward(sndr), env...)` if that expression is well-formed; otherwise, `std::forward(sndr)`. -2. Returns: e. +2. Returns: `e`. 3. Remarks: The exception specification is equivalent to noexcept(e). @@ -6957,14 +6987,14 @@ template <sender Sndr, queryable Env> constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept; -4. Let e be the expression +4. Let `e` be the expression `tag_of_t().transform_env(std::forward(sndr), std::forward(env))` if that expression is well-formed; otherwise, `static_cast(std::forward(env))`. 5. Mandates: noexcept(e) is `true`. -6. Returns: e. +6. Returns: `e`.
 template<class Tag, sender Sndr, class... Args>
@@ -6972,12 +7002,12 @@ template<class Tag, sender Sndr, class... Args>
     noexcept(see below);
 
-7. Let e be the expression +7. Let `e` be the expression `Tag().apply_sender(std::forward(sndr), std::forward(args)...)`. -8. Constraints: e is a well-formed expression. +8. Constraints: `e` is a well-formed expression. -9. Returns: e. +9. Returns: `e`. 10. Remarks: The exception specification is equivalent to noexcept(e). @@ -6985,23 +7015,25 @@ template<class Tag, sender Sndr, class... Args> ### `execution::transform_sender` [exec.snd.transform] ### {#spec-execution.sender_transform}
-template<class Domain, sender Sndr, queryable... Env>
-    requires (sizeof...(Env) <= 1)
-  constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env)
-    noexcept(see below);
+namespace std::execution {
+  template<class Domain, sender Sndr, queryable... Env>
+      requires (sizeof...(Env) <= 1)
+    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env)
+      noexcept(see below);
+}
 
-1. Let transformed-sndr be the expression +1. Let `transformed-sndr` be the expression `dom.transform_sender(std::forward(sndr), env...)` if that expression is well-formed; otherwise, `default_domain().transform_sender(std::forward(sndr), env...)`. Let - final-sndr be the expression - transformed-sndr if transformed-sndr + `final-sndr` be the expression + `transformed-sndr` if `transformed-sndr` and `sndr` have the same type ignoring *cv* qualifiers; otherwise, it is the expression transform_sender(dom, transformed-sndr, env...). -2. Returns: final-sndr. +2. Returns: `final-sndr`. 3. Remarks: The exception specification is equivalent to noexcept(final-sndr). @@ -7009,11 +7041,13 @@ template<class Domain, sender Sndr, queryable... Env> ### `execution::transform_env` [exec.snd.transform.env] ### {#spec-execution.env_transform}
-template<class Domain, sender Sndr, queryable Env>
-  constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+namespace std::execution {
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+}
 
-1. Let e be the expression +1. Let `e` be the expression `dom.transform_env(std::forward(sndr), std::forward(env))` if that expression is well-formed; otherwise, `default_domain().transform_env(std::forward(sndr), @@ -7021,26 +7055,28 @@ template<class Domain, sender Sndr, queryable Env> 2. Mandates: noexcept(e) is `true`. -2. Returns: e. +2. Returns: `e`. ### `execution::apply_sender` [exec.snd.apply] ### {#spec-execution.apply_sender}
-template<class Domain, class Tag, sender Sndr, class... Args>
-  constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args)
-    noexcept(see below);
+namespace std::execution {
+  template<class Domain, class Tag, sender Sndr, class... Args>
+    constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args)
+      noexcept(see below);
+}
 
-1. Let e be the expression `dom.apply_sender(Tag(), +1. Let `e` be the expression `dom.apply_sender(Tag(), std::forward(sndr), std::forward(args)...)` if that expression is well-formed; otherwise, `default_domain().apply_sender(Tag(), std::forward(sndr), std::forward(args)...)`. -2. Constraints: The expression e is well-formed. +2. Constraints: The expression `e` is well-formed. -1. Returns: e. +3. Returns: `e`. -2. Remarks: The exception specification is equivalent to +4. Remarks: The exception specification is equivalent to noexcept(e). ### `execution::get_completion_signatures` [exec.getcomplsigs] ### {#spec-execution.getcomplsigs} @@ -7071,7 +7107,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. Let `rcvr` be an rvalue receiver of type `Rcvr`, and let `Sndr` be the type of a sender such that `sender_in>` is `true`. Let `Sigs...` be the template arguments of the `completion_signatures` specialization named by - `completion_signatures_of_t>`. Let CSO be + `completion_signatures_of_t>`. Let `CSO` be a completion function. If sender `Sndr` or its operation state cause the expression CSO(rcvr, args...) to be potentially evaluated ([basic.def.odr]) then there shall be a signature `Sig` in `Sigs...` such @@ -7088,53 +7124,57 @@ template<class Domain, class Tag, sender Sndr, class... Args> `decltype((rcvr))`, and let `DS` and `DR` be the decayed types of `Sndr` and `Rcvr`, respectively. -3. Let connect-awaitable-promise be the following class: +3. Let `connect-awaitable-promise` be the following class:
-    struct connect-awaitable-promise
-      : with-await-transform<connect-awaitable-promise> {
-      DR& rcvr; // exposition only
+    namespace std::execution {
+      struct connect-awaitable-promise
+        : with-await-transform<connect-awaitable-promise> {
+        DR& rcvr; // exposition only
 
-      connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
+        connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
 
-      suspend_always initial_suspend() noexcept { return {}; }
-      [[noreturn]] suspend_always final_suspend() noexcept { terminate(); }
-      [[noreturn]] void unhandled_exception() noexcept { terminate(); }
-      [[noreturn]] void return_void() noexcept { terminate(); }
+        suspend_always initial_suspend() noexcept { return {}; }
+        [[noreturn]] suspend_always final_suspend() noexcept { terminate(); }
+        [[noreturn]] void unhandled_exception() noexcept { terminate(); }
+        [[noreturn]] void return_void() noexcept { terminate(); }
 
-      coroutine_handle<> unhandled_stopped() noexcept {
-        set_stopped((DR&&) rcvr);
-        return noop_coroutine();
-      }
+        coroutine_handle<> unhandled_stopped() noexcept {
+          set_stopped((DR&&) rcvr);
+          return noop_coroutine();
+        }
 
-      operation-state-task get_return_object() noexcept {
-        return operation-state-task{
-          coroutine_handle<connect-awaitable-promise>::from_promise(*this)};
-      }
+        operation-state-task get_return_object() noexcept {
+          return operation-state-task{
+            coroutine_handle<connect-awaitable-promise>::from_promise(*this)};
+        }
 
-      env_of_t<const DR&> get_env() const noexcept {
-        return execution::get_env(rcvr);
-      }
-    };
+        env_of_t<const DR&> get_env() const noexcept {
+          return execution::get_env(rcvr);
+        }
+      };
+    }
     
-4. Let operation-state-task be the following class: +4. Let `operation-state-task` be the following class:
-    struct operation-state-task {
-      using operation_state_concept = operation_state_t;
-      using promise_type = connect-awaitable-promise;
-      coroutine_handle<> coro; // exposition only
-
-      explicit operation-state-task(coroutine_handle<> h) noexcept : coro(h) {}
-      operation-state-task(operation-state-task&& o) noexcept
-        : coro(exchange(o.coro, {})) {}
-      ~operation-state-task() { if (coro) coro.destroy(); }
-
-      void start() & noexcept {
-        coro.resume();
-      }
-    };
+    namespace std::execution {
+      struct operation-state-task {
+        using operation_state_concept = operation_state_t;
+        using promise_type = connect-awaitable-promise;
+        coroutine_handle<> coro; // exposition only
+
+        explicit operation-state-task(coroutine_handle<> h) noexcept : coro(h) {}
+        operation-state-task(operation-state-task&& o) noexcept
+          : coro(exchange(o.coro, {})) {}
+        ~operation-state-task() { if (coro) coro.destroy(); }
+
+        void start() & noexcept {
+          coro.resume();
+        }
+      };
+    }
     
5. Let `V` name the type await-result-type<DS, @@ -7147,37 +7187,39 @@ template<class Domain, class Tag, sender Sndr, class... Args> set_stopped_t()> - and let connect-awaitable be an exposition-only + and let `connect-awaitable` be an exposition-only coroutine defined as follows:
-    template<class Fun, class... Ts>
-    auto suspend-complete(Fun fun, Ts&&... as) noexcept { // exposition only
-      auto fn = [&, fun]() noexcept { fun(std::forward<Ts>(as)...); };
+    namespace std::execution {
+      template<class Fun, class... Ts>
+      auto suspend-complete(Fun fun, Ts&&... as) noexcept { // exposition only
+        auto fn = [&, fun]() noexcept { fun(std::forward<Ts>(as)...); };
 
-      struct awaiter {
-        decltype(fn) fn;
+        struct awaiter {
+          decltype(fn) fn;
 
-        static bool await_ready() noexcept { return false; }
-        void await_suspend(coroutine_handle<>) noexcept { fn(); }
-        [[noreturn]] void await_resume() noexcept { unreachable(); }
+          static bool await_ready() noexcept { return false; }
+          void await_suspend(coroutine_handle<>) noexcept { fn(); }
+          [[noreturn]] void await_resume() noexcept { unreachable(); }
+        };
+        return awaiter{fn};
       };
-      return awaiter{fn};
-    };
 
-    operation-state-task connect-awaitable(DS sndr, DR rcvr) requires receiver_of<DR, Sigs> {
-      exception_ptr ep;
-      try {
-        if constexpr (same_as<V, void>) {
-          co_await std::move(sndr);
-          co_await suspend-complete(set_value, std::move(rcvr));
-        } else {
-          co_await suspend-complete(set_value, std::move(rcvr), co_await std::move(sndr));
+      operation-state-task connect-awaitable(DS sndr, DR rcvr) requires receiver_of<DR, Sigs> {
+        exception_ptr ep;
+        try {
+          if constexpr (same_as<V, void>) {
+            co_await std::move(sndr);
+            co_await suspend-complete(set_value, std::move(rcvr));
+          } else {
+            co_await suspend-complete(set_value, std::move(rcvr), co_await std::move(sndr));
+          }
+        } catch(...) {
+          ep = current_exception();
         }
-      } catch(...) {
-        ep = current_exception();
+        co_await suspend-complete(set_error, std::move(rcvr), std::move(ep));
       }
-      co_await suspend-complete(set_error, std::move(rcvr), std::move(ep));
     }
     
@@ -7220,37 +7262,39 @@ template<class Domain, class Tag, sender Sndr, class... Args> stopped completion operation respectively. 2. The names `just`, `just_error`, and `just_stopped` denote customization - point objects. Let just-cpo be one of `just`, + point objects. Let `just-cpo` be one of `just`, `just_error`, or `just_stopped`. For a pack of subexpressions `ts`, let `Ts` be the template parameter pack `decltype((ts))`. The expression just-cpo(ts...) is ill-formed if: - (movable-value<Ts> &&...) is `false`, or - - just-cpo is `just_error` and `sizeof...(ts) == 1` + - `just-cpo` is `just_error` and `sizeof...(ts) == 1` is `false`, or - - just-cpo is `just_stopped` and `sizeof...(ts) == 0` + - `just-cpo` is `just_stopped` and `sizeof...(ts) == 0` is `false`; Otherwise, it is expression-equivalent to make-sender(just-cpo, product-type{vs...}). -3. For `just`, `just_error`, and `just_stopped`, let set-cpo +3. For `just`, `just_error`, and `just_stopped`, let `set-cpo` be `set_value`, `set_error`, and `set_stopped` respectively. The - exposition-only class template impls-for - ([exec.snd.general]) is specialized for just-cpo as + exposition-only class template `impls-for` + ([exec.snd.general]) is specialized for `just-cpo` as follows:
-        template<>
-        struct impls-for<decayed-typeof<just-cpo>> : default-impls {
-          static constexpr auto start =
-            [](auto& state, auto& rcvr) noexcept -> void {
-              auto& [...ts] = state;
-              set-cpo(std::move(rcvr), std::move(ts)...);
-            };
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<decayed-typeof<just-cpo>> : default-impls {
+            static constexpr auto start =
+              [](auto& state, auto& rcvr) noexcept -> void {
+                auto& [...ts] = state;
+                set-cpo(std::move(rcvr), std::move(ts)...);
+              };
+          };
+        }
         
#### `execution::read` [exec.read] #### {#spec-execution.senders.read} @@ -7263,17 +7307,19 @@ template<class Domain, class Tag, sender Sndr, class... Args> the expression `read(q)` is expression-equivalent to make-sender(read, q). -3. The exposition-only class template impls-for ([exec.snd.general]) +3. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `read` as follows:
-    template<>
-    struct impls-for<decayed-typeof<read>> : default-impls {
-      static constexpr auto start =
-        [](auto query, auto& rcvr) noexcept -> void {
-          TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
-        };
-    };
+    namespace std::execution {
+      template<>
+      struct impls-for<decayed-typeof<read>> : default-impls {
+        static constexpr auto start =
+          [](auto query, auto& rcvr) noexcept -> void {
+            TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
+          };
+      };
+    }
     
### Sender adaptors [exec.adapt] ### {#spec-execution.senders.adapt} @@ -7454,17 +7500,19 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(transfer, sch, sndr)); -4. The exposition-only class template impls-for is specialized +4. The exposition-only class template `impls-for` is specialized for `transfer_t` as follows:
-        template<>
-        struct impls-for<transfer_t> : default-impls {
-          static constexpr auto get_attrs =
-            [](const auto& data, const auto& child) noexcept -> decltype(auto) {
-              return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
-            };
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<transfer_t> : default-impls {
+            static constexpr auto get_attrs =
+              [](const auto& data, const auto& child) noexcept -> decltype(auto) {
+                return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
+              };
+          };
+        }
         
5. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If @@ -7513,17 +7561,19 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(schedule_from, sch, sndr)); -4. The exposition-only class template impls-for +4. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `schedule_from_t` as follows:
-        template<>
-        struct impls-for<schedule_from_t> : default-impls {
-          static constexpr auto get-attrs = see below;
-          static constexpr auto get-state = see below;
-          static constexpr auto complete = see below;
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<schedule_from_t> : default-impls {
+            static constexpr auto get-attrs = see below;
+            static constexpr auto get-state = see below;
+            static constexpr auto complete = see below;
+          };
+        }
         
1. The member impls-for<schedule_from_t>::get-attrs is initialized @@ -7574,40 +7624,43 @@ template<class Domain, class Tag, sender Sndr, class... Args> variant<monostate, as-tuple<Sigs>...>, except with duplicate types removed. - 3. Let `receiver-type` denote the following class: + 3. Let `receiver-type` denote the following exposition-only + class:
-                struct receiver-type {
-                  using receiver_concept = receiver_t;
-                  state-type* state; // exposition only
-
-                  Rcvr&& base() && noexcept { return std::move(state->rcvr); }
-                  const Rcvr& base() const & noexcept { return state->rcvr; }
-
-                  void set_value() && noexcept {
-                    visit(
-                      [this]<class Tuple>(Tuple& result) noexcept -> void {
-                        if constexpr (!same_as<monostate, Tuple>) {
-                          auto& [tag, ...args] = result;
-                          tag(std::move(state->rcvr), std::move(args)...);
-                        }
-                      },
-                      state->async-result);
-                  }
-
-                  template<class Error>
-                  void set_error(Error&& err) && noexcept {
-                    execution::set_error(std::move(state->rcvr), std::forward<Error>(err));
-                  }
-
-                  void set_stopped() && noexcept {
-                    execution::set_stopped(std::move(state->rcvr));
-                  }
-
-                  decltype(auto) get_env() const noexcept {
-                    return FWD-ENV(execution::get_env(state->rcvr));
-                  }
-                };
+                namespace std::execution {
+                  struct receiver-type {
+                    using receiver_concept = receiver_t;
+                    state-type* state; // exposition only
+
+                    Rcvr&& base() && noexcept { return std::move(state->rcvr); }
+                    const Rcvr& base() const & noexcept { return state->rcvr; }
+
+                    void set_value() && noexcept {
+                      visit(
+                        [this]<class Tuple>(Tuple& result) noexcept -> void {
+                          if constexpr (!same_as<monostate, Tuple>) {
+                            auto& [tag, ...args] = result;
+                            tag(std::move(state->rcvr), std::move(args)...);
+                          }
+                        },
+                        state->async-result);
+                    }
+
+                    template<class Error>
+                    void set_error(Error&& err) && noexcept {
+                      execution::set_error(std::move(state->rcvr), std::forward<Error>(err));
+                    }
+
+                    void set_stopped() && noexcept {
+                      execution::set_stopped(std::move(state->rcvr));
+                    }
+
+                    decltype(auto) get_env() const noexcept {
+                      return FWD-ENV(execution::get_env(state->rcvr));
+                    }
+                  };
+                }
                 
3. The member impls-for<schedule_from_t>::complete @@ -7652,10 +7705,10 @@ template<class Domain, class Tag, sender Sndr, class... Args> of the invocable as a value completion. 2. The names `then`, `upon_error`, and `upon_stopped` denote customization point - objects. Let the expression then-cpo be one of `then`, + objects. Let the expression `then-cpo` be one of `then`, `upon_error`, or `upon_stopped`. For subexpressions `sndr` and `f`, let `Sndr` be `decltype((sndr))` and let `F` be the decayed type of `f`. If `Sndr` does not - satisfy `sender`, or `F` does not satisfy movable-value, + satisfy `sender`, or `F` does not satisfy `movable-value`, then-cpo(sndr, f) is ill-formed. 3. Otherwise, the expression then-cpo(sndr, f) is @@ -7667,25 +7720,27 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(then-cpo, f, sndr)); -4. For `then`, `upon_error`, and `upon_stopped`, let set-cpo +4. For `then`, `upon_error`, and `upon_stopped`, let `set-cpo` be `set_value`, `set_error`, and `set_stopped` respectively. The - exposition-only class template impls-for + exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `then-cpo` as follows:
-        template<>
-        struct impls-for<decayed-typeof<then-cpo>> : default-impls {
-          static constexpr auto complete =
-            []<class Tag, class... Args>
-              (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
-                if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
-                  TRY-SET-VALUE(std::move(rcvr),
-                                invoke(std::move(fn), std::forward<Args>(args)...));
-                } else {
-                  Tag()(std::move(rcvr), std::forward<Args>(args)...);
-                }
-              };
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<decayed-typeof<then-cpo>> : default-impls {
+            static constexpr auto complete =
+              []<class Tag, class... Args>
+                (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
+                  if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
+                    TRY-SET-VALUE(std::move(rcvr),
+                                  invoke(std::move(fn), std::forward<Args>(args)...));
+                  } else {
+                    Tag()(std::move(rcvr), std::forward<Args>(args)...);
+                  }
+                };
+          };
+        }
         
5. The expression then-cpo(sndr, f) has undefined behavior @@ -7705,9 +7760,9 @@ template<class Domain, class Tag, sender Sndr, class... Args> operation by passing the sender's result datums to a user-specified callable, which returns a new sender that is connected and started. -2. Let the expression let-cpo be one of `let_value`, - `let_error`, or `let_stopped` and let set-cpo be the - completion function that corresponds to let-cpo +2. Let the expression `let-cpo` be one of `let_value`, + `let_error`, or `let_stopped` and let `set-cpo` be the + completion function that corresponds to `let-cpo` (`set_value` for `let_value`, etc.). For a subexpression `sndr`, let let-env(sndr) be expression-equivalent to the first well-formed expression below: @@ -7721,7 +7776,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 3. The names `let_value`, `let_error`, and `let_stopped` denote customization point objects. For subexpressions `sndr` and `f`, let `Sndr` be `decltype((sndr))`, let `F` be the decayed type of `f`. If `Sndr` does not satisfy `sender` or if `F` - does not satisfy movable-value, the expression + does not satisfy `movable-value`, the expression let-cpo(sndr, f) is ill-formed. If `F` does not satisfy `invocable`, the expression `let_stopped(sndr, f)` is ill-formed. @@ -7734,36 +7789,40 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(let-cpo, f, sndr)); -5. The exposition-only class template impls-for - ([exec.snd.general]) is specialized for let-cpo as +5. The exposition-only class template `impls-for` + ([exec.snd.general]) is specialized for `let-cpo` as follows:
-        template<class State, class Rcvr, class... Args>
-        void let-bind(State& state, Rcvr& rcvr, Args&&... args); // exposition only
-
-        template<>
-        struct impls-for<decayed-typeof<let-cpo>> : default-impls {
-          static constexpr auto get-state = see below;
-          static constexpr auto complete = see below;
-        };
+        namespace std::execution {
+          template<class State, class Rcvr, class... Args>
+          void let-bind(State& state, Rcvr& rcvr, Args&&... args); // exposition only
+
+          template<>
+          struct impls-for<decayed-typeof<let-cpo>> : default-impls {
+            static constexpr auto get-state = see below;
+            static constexpr auto complete = see below;
+          };
+        }
         
1. Let `receiver2` denote the following exposition-only class template:
-            template<class Rcvr, class Env>
-            struct receiver2 : Rcvr {
-              explicit receiver2(Rcvr rcvr, Env env)
-                : Rcvr(std::move(rcvr)), env(std::move(env)) {}
-
-              auto get_env() const noexcept {
-                const Rcvr& rcvr = *this;
-                return JOIN-ENV(env, FWD-ENV(execution::get_env(rcvr)));
-              }
+            namespace std::execution {
+              template<class Rcvr, class Env>
+              struct receiver2 : Rcvr {
+                explicit receiver2(Rcvr rcvr, Env env)
+                  : Rcvr(std::move(rcvr)), env(std::move(env)) {}
+
+                auto get_env() const noexcept {
+                  const Rcvr& rcvr = *this;
+                  return JOIN-ENV(env, FWD-ENV(execution::get_env(rcvr)));
+                }
 
-              Env env; // exposition only
-            };
+                Env env; // exposition only
+              };
+            }
             
2. impls-for<tag_t<let-cpo>>::get-state is @@ -7848,7 +7907,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> rcvr)` has undefined behavior unless it creates an asynchronous operation ([async.ops]) that, when started: - - invokes `f` when set-cpo is called with `sndr`'s + - invokes `f` when `set-cpo` is called with `sndr`'s result datums, - makes its completion dependent on the completion of a sender returned @@ -7864,7 +7923,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> `sndr`, `shape`, and `f`, let `Sndr` be `decltype((sndr))`, let `Shape` be the decayed type of `shape`, and let `F` be the decayed type of `f`. If `Sndr` does not satisfy `sender`, or if `Shape` does not satisfy `integral`, - or if `F` does not satisfy movable-value, bulk(sndr, + or if `F` does not satisfy `movable-value`, bulk(sndr, shape, f) is ill-formed. 3. Otherwise, the expression bulk(sndr, shape, f) is @@ -7876,14 +7935,16 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(bulk, product-type{shape, f}, sndr)); -4. The exposition-only class template impls-for +4. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `bulk_t` as follows:
-        template<>
-        struct impls-for<bulk_t> : default-impls {
-          static constexpr auto complete = see below;
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<bulk_t> : default-impls {
+            static constexpr auto complete = see below;
+          };
+        }
         
1. The member impls-for<bulk_t>::complete is @@ -7931,7 +7992,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> multiple times. `ensure_started` eagerly starts the execution of a sender, returning a sender that is usable as input to additional sender algorithms. -2. Let shared-env be the type of an environment such that, +2. Let `shared-env` be the type of an environment such that, given an instance `env`, the expression `get_stop_token(env)` is well-formed and has type `in_place_stop_token`. @@ -7942,7 +8003,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> `constructible_from>, env_of_t>` is `false`, shared-cpo(sndr) is ill-formed. - Although it has not yet been approved by LEWG, there + Although it has not yet been approved by LEWG, there is a bug in the current wording that makes it impossible to safely copy the attributes of a sender; it may have reference semantics, leading to a dangling reference. I am striking this part for now and will bring a fix to @@ -7965,28 +8026,30 @@ template<class Domain, class Tag, sender Sndr, class... Args> 5. Let `local-state` denote the following exposition-only class:
-    struct local-state-base {
-      virtual ~local-state-base() = default;
-      virtual void notify() noexcept = 0;
-      virtual void detach() noexcept = 0;
-    };
+    namespace std::execution {
+      struct local-state-base {
+        virtual ~local-state-base() = default;
+        virtual void notify() noexcept = 0;
+        virtual void detach() noexcept = 0;
+      };
 
-    template<class Sndr, class Rcvr>
-    struct local-state : local-state-base {
-      using on-stop-request = see below;
-      using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>::
-                                  template callback_type<on-stop-request>;
+      template<class Sndr, class Rcvr>
+      struct local-state : local-state-base {
+        using on-stop-request = see below;
+        using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>::
+                                    template callback_type<on-stop-request>;
 
-      local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
-      ~local-state();
+        local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
+        ~local-state();
 
-      void notify() noexcept override;
-      void detach() noexcept override;
+        void notify() noexcept override;
+        void detach() noexcept override;
 
-      optional<on-stop-callback> on_stop;
-      shared-state<Sndr>* sh_state;
-      Rcvr* rcvr;
-    };
+        optional<on-stop-callback> on_stop;
+        shared-state<Sndr>* sh_state;
+        Rcvr* rcvr;
+      };
+    }
     
1.
@@ -8047,77 +8110,81 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     template:
 
     
-    template<class Sndr>
-    struct shared-receiver {
-      using receiver_concept = receiver_t;
+    namespace std::execution {
+      template<class Sndr>
+      struct shared-receiver {
+        using receiver_concept = receiver_t;
 
-      template<class Tag, class... Args>
-      void complete(Tag, Args&&... args) noexcept { // exposition only
-        try {
-          using tuple_t = decayed-tuple<Tag, Args...>;
-          sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
-        } catch (...) {
-          using tuple_t = tuple<set_error_t, exception_ptr>;
-          sh_state->result.template emplace<tuple_t>(set_error, current_exception());
+        template<class Tag, class... Args>
+        void complete(Tag, Args&&... args) noexcept { // exposition only
+          try {
+            using tuple_t = decayed-tuple<Tag, Args...>;
+            sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
+          } catch (...) {
+            using tuple_t = tuple<set_error_t, exception_ptr>;
+            sh_state->result.template emplace<tuple_t>(set_error, current_exception());
+          }
+          sh_state->notify();
         }
-        sh_state->notify();
-      }
 
-      template<class... Args>
-      void set_value(Args&&... args) && noexcept {
-        complete(execution::set_value, std::forward<Args>(args)...);
-      }
+        template<class... Args>
+        void set_value(Args&&... args) && noexcept {
+          complete(execution::set_value, std::forward<Args>(args)...);
+        }
 
-      template<class Error>
-      void set_error(Error&& err) && noexcept {
-        complete(execution::set_error, std::forward<Error>(err));
-      }
+        template<class Error>
+        void set_error(Error&& err) && noexcept {
+          complete(execution::set_error, std::forward<Error>(err));
+        }
 
-      void set_stopped() && noexcept {
-        complete(execution::set_stopped);
-      }
+        void set_stopped() && noexcept {
+          complete(execution::set_stopped);
+        }
 
-      struct env { // exposition only
-        shared-state<Sndr>* sh-state; // exposition only
+        struct env { // exposition only
+          shared-state<Sndr>* sh-state; // exposition only
 
-        in_place_stop_source query(get_stop_token_t) const noexcept {
-          return sh-state->stop_src.get_token();
-        }
-      };
+          in_place_stop_source query(get_stop_token_t) const noexcept {
+            return sh-state->stop_src.get_token();
+          }
+        };
 
-      env get_env() const noexcept {
-        return env{sh_state};
-      }
+        env get_env() const noexcept {
+          return env{sh_state};
+        }
 
-      shared-state<Sndr>* sh_state;
-    };
+        shared-state<Sndr>* sh_state;
+      };
+    }
     
7. Let `shared-state` denote the following exposition-only class template:
-    template<class Sndr>
-    struct shared-state {
-      using variant-type = see below;
-      using state-list-type = see below;
-      using state-flag-type = see below;
-
-      explicit shared-state(Sndr&& sndr);
-
-      void start-op() noexcept;
-      void notify() noexcept;
-      void detach() noexcept;
-      void inc-ref() noexcept;
-      void dec-ref() noexcept;
-
-      in_place_stop_source stop_src{};
-      variant-type result{};
-      state-list-type waiting_states;
-      state-flag-type completed;
-      atomic<size_t> ref_count{1};
-      connect_result_t<Sndr, shared-receiver<Sndr>> op_state;
-    };
+    namespace std::execution {
+      template<class Sndr>
+      struct shared-state {
+        using variant-type = see below;
+        using state-list-type = see below;
+        using state-flag-type = see below;
+
+        explicit shared-state(Sndr&& sndr);
+
+        void start-op() noexcept;
+        void notify() noexcept;
+        void detach() noexcept;
+        void inc-ref() noexcept;
+        void dec-ref() noexcept;
+
+        in_place_stop_source stop_src{};
+        variant-type result{};
+        state-list-type waiting_states;
+        state-flag-type completed;
+        atomic<size_t> ref_count{1};
+        connect_result_t<Sndr, shared-receiver<Sndr>> op_state;
+      };
+    }
     
1. Let `Sigs` be a pack of the arguments to the @@ -8211,16 +8278,18 @@ template<class Domain, class Tag, sender Sndr, class... Args> and finally, it decrements the reference count by calling sh_state->dec-ref(). -9. The exposition-only class template impls-for - ([exec.snd.general]) is specialized for shared-impl-tag +9. The exposition-only class template `impls-for` + ([exec.snd.general]) is specialized for `shared-impl-tag` as follows:
-        template<>
-        struct impls-for<shared-impl-tag> : default-impls {
-          static constexpr auto get-state = see below;
-          static constexpr auto start = see below;
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<shared-impl-tag> : default-impls {
+            static constexpr auto get-state = see below;
+            static constexpr auto start = see below;
+          };
+        }
         
1. The member @@ -8241,7 +8310,8 @@ template<class Domain, class Tag, sender Sndr, class... Args>
         template <class Sndr, class Rcvr>
-        void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
+ void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept; +
1. *Effects:* @@ -8313,7 +8383,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> * If the types of the expressions get-domain-early(sndri) do not share - a common type ([meta.trans.other]) for all values of i. + a common type ([meta.trans.other]) for all values of `i`. Otherwise, let `CD` be the common type of the input senders' domains. @@ -8326,18 +8396,20 @@ template<class Domain, class Tag, sender Sndr, class... Args> make-sender(when_all, {}, sndr0, ... sndrn-1)); -4. The exposition-only class template impls-for +4. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `when_all_t` as follows:
-        template<>
-        struct impls-for<when_all_t> : default-impls {
-          static constexpr auto get-attrs = see below;
-          static constexpr auto get-env = see below;
-          static constexpr auto get-state = see below;
-          static constexpr auto start = see below;
-          static constexpr auto complete = see below;
-        };
+        namespace std::execution {
+          template<>
+          struct impls-for<when_all_t> : default-impls {
+            static constexpr auto get-attrs = see below;
+            static constexpr auto get-env = see below;
+            static constexpr auto get-state = see below;
+            static constexpr auto start = see below;
+            static constexpr auto complete = see below;
+          };
+        }
         
1. The member impls-for<when_all_t>::get-attrs @@ -8434,7 +8506,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 3. The alias `errors_variant` denotes the type variant<none-such, copy-fail, Es...> with duplicate types removed, where - Es is the pack of the decayed types of all the + `Es` is the pack of the decayed types of all the input senders' possible error result datums. 4. The member void state::complete(Rcvr& rcvr) @@ -8578,14 +8650,16 @@ template<class Domain, class Tag, sender Sndr, class... Args> 1. `into_variant` adapts a sender with multiple value completion signatures into a sender with just one consisting of a `variant` of `tuple`s. -2. The template into-variant-type computes the type sent by +2. The template `into-variant-type` computes the type sent by a sender returned from `into_variant`.
-        template<class Sndr, class Env>
-            requires sender_in<Sndr, Env>
-          using into-variant-type =
-            value_types_of_t<Sndr, Env>;
+    namespace std::execution {
+      template<class Sndr, class Env>
+          requires sender_in<Sndr, Env>
+        using into-variant-type =
+          value_types_of_t<Sndr, Env>;
+    }
     
3. The name `into_variant` denotes a customization point object. For a @@ -8604,11 +8678,13 @@ template<class Domain, class Tag, sender Sndr, class... Args> specialized for `into_variant` as follows:
-    template<>
-    struct impls-for<into_variant_t> : default-impls {
-      static constexpr auto get-state = see below;
-      static constexpr auto complete = see below;
-    };
+    namespace std::execution {
+      template<>
+      struct impls-for<into_variant_t> : default-impls {
+        static constexpr auto get-state = see below;
+        static constexpr auto complete = see below;
+      };
+    }
     
1. The member @@ -8678,7 +8754,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> that never completes with stopped, reporting cancellation by completing with an error. -2. The name `stopped_as_error` denotes a customization point object. For some subexpressions `sndr` and `err`, let `Sndr` be `decltype((sndr))` and let `Err` be `decltype((err))`. If the type `Sndr` does not satisfy `sender` or if the type `Err` doesn't satisfy movable-value, `stopped_as_error(sndr, err)` is ill-formed. Otherwise, the expression `stopped_as_error(sndr, err)` is expression-equivalent to: +2. The name `stopped_as_error` denotes a customization point object. For some subexpressions `sndr` and `err`, let `Sndr` be `decltype((sndr))` and let `Err` be `decltype((err))`. If the type `Sndr` does not satisfy `sender` or if the type `Err` doesn't satisfy `movable-value`, `stopped_as_error(sndr, err)` is ill-formed. Otherwise, the expression `stopped_as_error(sndr, err)` is expression-equivalent to:
     transform_sender(
@@ -8723,30 +8799,32 @@ template<class Domain, class Tag, sender Sndr, class... Args>
     calling `start_detached(sndr)` is undefined.
 
 3. Let `sndr` be a subexpression such that `Sndr` is `decltype((sndr))`, and let
-    detached-receiver and
-    detached-operation be the following exposition-only
+    `detached-receiver` and
+    `detached-operation` be the following exposition-only
     class templates:
 
     
-    template<class Sndr>
-    struct detached-receiver {
-      using receiver_concept = receiver_t;
-      detached-operation<Sndr>* op; // exposition only
-
-      void set_value() && noexcept { delete op; }
-      void set_error() && noexcept { terminate(); }
-      void set_stopped() && noexcept { delete op; }
-      empty_env get_env() const noexcept { return {}; }
-    };
+    namespace std::execution {
+      template<class Sndr>
+      struct detached-receiver {
+        using receiver_concept = receiver_t;
+        detached-operation<Sndr>* op; // exposition only
+
+        void set_value() && noexcept { delete op; }
+        void set_error() && noexcept { terminate(); }
+        void set_stopped() && noexcept { delete op; }
+        empty_env get_env() const noexcept { return {}; }
+      };
 
-    template<class Sndr>
-    struct detached-operation {
-      connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only
+      template<class Sndr>
+      struct detached-operation {
+        connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only
 
-      explicit detached-operation(Sndr&& sndr)
-        : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this}))
-      {}
-    };
+        explicit detached-operation(Sndr&& sndr)
+          : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this}))
+        {}
+      };
+    }
     
4. If sender_to<Sndr, detached-receiver<Sndr>> is `false`, the @@ -8761,33 +8839,36 @@ template<class Domain, class Tag, sender Sndr, class... Args> completes and to return its async result. `sync_wait` mandates that the input sender has exactly one value completion signature. -2. Let sync-wait-env be the following exposition-only class +2. Let `sync-wait-env` be the following exposition-only class type:
-    struct sync-wait-env {
-      execution::run_loop* loop; // exposition only
+    namespace std::this_thread {
+      struct sync-wait-env {
+        execution::run_loop* loop; // exposition only
 
-      auto query(execution::get_scheduler_t) const noexcept { loop->get_scheduler(); }
-      auto query(execution::get_delegatee_scheduler_t) const noexcept { loop->get_scheduler(); }
-    };
+        auto query(execution::get_scheduler_t) const noexcept { loop->get_scheduler(); }
+        auto query(execution::get_delegatee_scheduler_t) const noexcept { loop->get_scheduler(); }
+      };
+    }
     
-3. Let sync-wait-result-type and - sync-wait-with-variant-result-type be exposition-only +3. Let `sync-wait-result-type` and + `sync-wait-with-variant-result-type` be exposition-only template aliases defined as follows:
-    template<sender_in<sync-wait-env> Sndr>
-      using sync-wait-result-type =
-        optional<value_types_of_t<Sndr, sync-wait-env, decayed-tuple, type_identity_t>>;
-
-    template<sender_in<sync-wait-env> Sndr>
-      using sync-wait-with-variant-result-type =
-        optional<into-variant-type<Sndr, sync-wait-env>>; // see [exec.into.variant]
+    namespace std::this_thread {
+      template<execution::sender_in<sync-wait-env> Sndr>
+        using sync-wait-result-type =
+          optional<execution::value_types_of_t<Sndr, sync-wait-env, decayed-tuple, type_identity_t>>;
+
+      template<execution::sender_in<sync-wait-env> Sndr>
+        using sync-wait-with-variant-result-type =
+          optional<execution::into-variant-type<Sndr, sync-wait-env>>; // see [exec.into.variant]
+    }
     
- 4. The name `this_thread::sync_wait` denotes a customization point object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If sender_in<Sndr, sync-wait-env> is `false`, the @@ -8805,40 +8886,42 @@ template<class Domain, class Tag, sender Sndr, class... Args> * same_as<decltype(e), sync-wait-result-type<Sndr>> is `true`, where - e is `apply_sender` the expression above. + `e` is `apply_sender` the expression above. -5. Let sync-wait-state and - sync-wait-receiver be the following exposition-only class +5. Let `sync-wait-state` and + `sync-wait-receiver` be the following exposition-only class templates:
-    template<class Sndr>
-    struct sync-wait-state { // exposition only
-      run_loop loop;
-      exception_ptr error;
-      sync-wait-result-type<Sndr> result;
-    };
+    namespace std::this_thread {
+      template<class Sndr>
+      struct sync-wait-state { // exposition only
+        execution::run_loop loop;
+        exception_ptr error;
+        sync-wait-result-type<Sndr> result;
+      };
 
-    template<class Sndr>
-    struct sync-wait-receiver {
-      using receiver_concept = receiver_t;
-      sync-wait-state<Sndr>* state; // exposition only
+      template<class Sndr>
+      struct sync-wait-receiver {
+        using receiver_concept = execution::receiver_t;
+        sync-wait-state<Sndr>* state; // exposition only
 
-      template<class... Args>
-      void set_value(Args&&... args) && noexcept;
+        template<class... Args>
+        void set_value(Args&&... args) && noexcept;
 
-      template<class Error>
-      void set_error(Error&& err) && noexcept;
+        template<class Error>
+        void set_error(Error&& err) && noexcept;
 
-      void set_stopped() && noexcept;
+        void set_stopped() && noexcept;
 
-      sync-wait-env get_env() const noexcept { return {&state->loop}; }
-    };
+        sync-wait-env get_env() const noexcept { return {&state->loop}; }
+      };
+    }
     
1.
         template<class... Args>
-        void sync-wait-receiver::set_value(Args&&... args) && noexcept;
+        void set_value(Args&&... args) && noexcept;
         
1. *Effects:* Equivalent to: @@ -8854,7 +8937,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2.
         template<class Error>
-        void sync-wait-receiver::set_error(Error&& err) && noexcept;
+        void set_error(Error&& err) && noexcept;
         
1. *Effects:* Equivalent to: @@ -8866,7 +8949,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> 3.
         template<class Error>
-        void sync-wait-receiver::set_stopped() && noexcept;
+        void set_stopped() && noexcept;
         
1. *Effects:* Equivalent to state->loop.finish(). @@ -8891,13 +8974,13 @@ template<class Domain, class Tag, sender Sndr, class... Args> 7. The behavior of `this_thread::sync_wait(sndr)` is undefined unless: - 1. It blocks the current thread of execution with forward progress guarantee - delegation ([intro.progress]) until the specified sender completes. - The default implementation of `sync_wait` - achieves forward progress guarantee delegation by providing a `run_loop` - scheduler via the `get_delegatee_scheduler` query on the - sync-wait-receiver's environment. The `run_loop` - is driven by the current thread of execution. + 1. It blocks the current thread of execution ([defns.block]) with forward + progress guarantee delegation ([intro.progress]) until the specified + sender completes. The default implementation of + `sync_wait` achieves forward progress guarantee delegation by providing + a `run_loop` scheduler via the `get_delegatee_scheduler` query on the + `sync-wait-receiver`'s environment. The `run_loop` is + driven by the current thread of execution. 2. It returns the specified sender's async results as follows: @@ -8927,7 +9010,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> - same_as<decltype(e), sync-wait-with-variant-result-type<Sndr>> is `true`, - where e is the expression above. + where `e` is the expression above. 9. If callable<sync_wait_t, Sndr> is `false`, the expression `sync_wait_with_variant.apply_sender(sndr)` is ill-formed. @@ -8943,16 +9026,17 @@ template<class Domain, class Tag, sender Sndr, class... Args> 10. The behavior of `this_thread::sync_wait_with_variant(sndr)` is undefined unless: - 1. It blocks the current thread of execution with forward progress guarantee - delegation ([intro.progress]) until the specified sender completes. - The default implementation of `sync_wait_with_variant` - achieves forward progress guarantee delegation by relying on the - forward progress guarantee delegation provided by `sync_wait`. + 1. It blocks the current thread of execution ([defns.block]) with forward + progress guarantee delegation ([intro.progress]) until the specified + sender completes. The default implementation of + `sync_wait_with_variant` achieves forward progress guarantee delegation + by relying on the forward progress guarantee delegation provided by + `sync_wait`. 2. It returns the specified sender's async results as follows: - 1. For a value completion, the result datums are returned - in a `variant` of `tuple`s in an engaged `optional` object. + 1. For a value completion, the result datums are returned in an engaged + `optional` object that contains a `variant` of `tuple`s. 2. For an error completion, the result datum is rethrown. @@ -8973,6 +9057,7 @@ template<class Domain, class Tag, sender Sndr, class... Args> query-or-default(get_domain, sch, default_domain()), execute, schedule(sch), f)
+ * Mandates: The type of the expression above is `void`. 3. For some subexpressions `sndr` and `f` where `F` is the decayed type of `f`, @@ -9025,12 +9110,12 @@ template<class Domain, class Tag, sender Sndr, class... Args> concept always-true = true; // exposition only - 1. A type `Fn` satisfies completion-signature if and + 1. A type `Fn` satisfies `completion-signature` if and only if it is a function type with one of the following forms: - * set_value_t(Vs...), where Vs + * set_value_t(Vs...), where `Vs` is an arbitrary parameter pack. - * set_error_t(Err), where Err is + * set_error_t(Err), where `Err` is an arbitrary type. * `set_stopped_t()` @@ -9044,55 +9129,57 @@ template<class Domain, class Tag, sender Sndr, class... Args> 2. Let `Fns...` be a template parameter pack of the arguments of the `completion_signatures` specialization named by `Completions`, let - TagFns be a template parameter pack of the function + `TagFns` be a template parameter pack of the function types in `Fns` whose return types are `Tag`, and let Tsn be a template parameter pack - of the function argument types in the n-th type in - TagFns. Then, given two variadic templates - Tuple and Variant, the type + of the function argument types in the `n`-th type in + `TagFns`. Then, given two variadic templates + `Tuple` and `Variant`, the type gather-signatures<Tag, Completions, Tuple, Variant> names the type META-APPLY(Variant, META-APPLY(Tuple, Ts0...), META-APPLY(Tuple, Ts1...), ... META-APPLY(Tuple, - Tsm-1...)), where m - is the size of the parameter pack TagFns and + Tsm-1...))
, where `m` + is the size of the parameter pack `TagFns` and META-APPLY(T, As...) is equivalent to:
         typename indirect-meta-apply<always-true<As...>>::template meta-apply<T, As...>;
         
- 3. The purpose of META-APPLY is + 3. The purpose of `META-APPLY` is to make it valid to use non-variadic templates as - Variant and Tuple arguments to - gather-signatures. + `Variant` and `Tuple` arguments to + `gather-signatures`. 4.
-    template<completion-signature... Fns>
-      struct completion_signatures {};
-
-    template<class Sndr,
-              class Env = empty_env,
-              template<class...> class Tuple = decayed-tuple,
-              template<class...> class Variant = variant-or-empty>
-        requires sender_in<Sndr, Env>
-      using value_types_of_t =
-          gather-signatures<set_value_t, completion_signatures_of_t<Sndr, Env>, Tuple, Variant>;
-
-    template<class Sndr,
-              class Env = empty_env,
-              template<class...> class Variant = variant-or-empty>
-        requires sender_in<Sndr, Env>
-      using error_types_of_t =
-          gather-signatures<set_error_t, completion_signatures_of_t<Sndr, Env>, type_identity_t, Variant>;
-
-    template<class Sndr, class Env = empty_env>
-        requires sender_in<Sndr, Env>
-      inline constexpr bool sends_stopped =
-          !same_as<
-            type-list<>,
-            gather-signatures<set_stopped_t, completion_signatures_of_t<Sndr, Env>, type-list, type-list>>;
+    namespace std::execution {
+      template<completion-signature... Fns>
+        struct completion_signatures {};
+
+      template<class Sndr,
+                class Env = empty_env,
+                template<class...> class Tuple = decayed-tuple,
+                template<class...> class Variant = variant-or-empty>
+          requires sender_in<Sndr, Env>
+        using value_types_of_t =
+            gather-signatures<set_value_t, completion_signatures_of_t<Sndr, Env>, Tuple, Variant>;
+
+      template<class Sndr,
+                class Env = empty_env,
+                template<class...> class Variant = variant-or-empty>
+          requires sender_in<Sndr, Env>
+        using error_types_of_t =
+            gather-signatures<set_error_t, completion_signatures_of_t<Sndr, Env>, type_identity_t, Variant>;
+
+      template<class Sndr, class Env = empty_env>
+          requires sender_in<Sndr, Env>
+        inline constexpr bool sends_stopped =
+            !same_as<
+              type-list<>,
+              gather-signatures<set_stopped_t, completion_signatures_of_t<Sndr, Env>, type-list, type-list>>;
+    }
     
### `execution::transform_completion_signatures` [exec.utils.tfxcmplsigs] ### {#spec-execution.snd_rec_utils.transform_completion_sigs} @@ -9135,15 +9222,17 @@ template<class Domain, class Tag, sender Sndr, class... Args> 4.
-    template<valid-completion-signatures InputSignatures,
-             valid-completion-signatures AdditionalSignatures =
-                 completion_signatures<>,
-             template<class...> class SetValue = default-set-value,
-             template<class> class SetError = default-set-error,
-             valid-completion-signatures SetStopped =
-                 completion_signatures<set_stopped_t()>>
-    using transform_completion_signatures =
-      completion_signatures<see below>;
+    namespace std::execution {
+      template<valid-completion-signatures InputSignatures,
+              valid-completion-signatures AdditionalSignatures =
+                  completion_signatures<>,
+              template<class...> class SetValue = default-set-value,
+              template<class> class SetError = default-set-error,
+              valid-completion-signatures SetStopped =
+                  completion_signatures<set_stopped_t()>>
+      using transform_completion_signatures =
+        completion_signatures<see below>;
+    }
     
1. `SetValue` shall name an alias template such that for any template @@ -9158,14 +9247,14 @@ template<class Domain, class Tag, sender Sndr, class... Args> Then: - 3. Let `Vs...` be a pack of the types in the type-list + 3. Let `Vs...` be a pack of the types in the `type-list` named by gather-signatures<set_value_t, InputSignatures, SetValue, type-list>. - 4. Let `Es...` be a pack of the types in the type-list + 4. Let `Es...` be a pack of the types in the `type-list` named by gather-signatures<set_error_t, InputSignatures, type_identity_t, error-list>, where - error-list is an alias template such that + `error-list` is an alias template such that error-list<Ts...> names type-list<SetError<Ts>...>. @@ -9212,33 +9301,35 @@ template<class Domain, class Tag, sender Sndr, class... Args> allocation-free.
-    class run_loop {
-      // [exec.run.loop.types] Associated types
-      class run-loop-scheduler; // exposition only
-      class run-loop-sender; // exposition only
-      struct run-loop-opstate-base { // exposition only
-        virtual void execute() = 0;
-        run_loop* loop;
-        run-loop-opstate-base* next;
+    namespace std::execution {
+      class run_loop {
+        // [exec.run.loop.types] Associated types
+        class run-loop-scheduler; // exposition only
+        class run-loop-sender; // exposition only
+        struct run-loop-opstate-base { // exposition only
+          virtual void execute() = 0;
+          run_loop* loop;
+          run-loop-opstate-base* next;
+        };
+        template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
+          using run-loop-opstate = unspecified; // exposition only
+
+        // [exec.run.loop.members] Member functions:
+        run-loop-opstate-base* pop_front(); // exposition only
+        void push_back(run-loop-opstate-base*); // exposition only
+
+      public:
+        // [exec.run.loop.ctor] construct/copy/destroy
+        run_loop() noexcept;
+        run_loop(run_loop&&) = delete;
+        ~run_loop();
+
+        // [exec.run.loop.members] Member functions:
+        run-loop-scheduler get_scheduler();
+        void run();
+        void finish();
       };
-      template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
-        using run-loop-opstate = unspecified; // exposition only
-
-      // [exec.run.loop.members] Member functions:
-      run-loop-opstate-base* pop_front(); // exposition only
-      void push_back(run-loop-opstate-base*); // exposition only
-
-     public:
-      // [exec.run.loop.ctor] construct/copy/destroy
-      run_loop() noexcept;
-      run_loop(run_loop&&) = delete;
-      ~run_loop();
-
-      // [exec.run.loop.members] Member functions:
-      run-loop-scheduler get_scheduler();
-      void run();
-      void finish();
-    };
+    }
     
#### Associated types [exec.run.loop.types] #### {#spec-execution.contexts.run_loop.types} @@ -9247,35 +9338,35 @@ template<class Domain, class Tag, sender Sndr, class... Args> class run-loop-scheduler; -1. run-loop-scheduler is an unspecified type that models +1. `run-loop-scheduler` is an unspecified type that models the `scheduler` concept. -2. Instances of run-loop-scheduler remain valid until the +2. Instances of `run-loop-scheduler` remain valid until the end of the lifetime of the `run_loop` instance from which they were obtained. -3. Two instances of run-loop-scheduler compare equal if +3. Two instances of `run-loop-scheduler` compare equal if and only if they were obtained from the same `run_loop` instance. -4. Let sch be an expression of type - run-loop-scheduler. The expression +4. Let `sch` be an expression of type + `run-loop-scheduler`. The expression schedule(sch) is not potentially-throwing and has type - run-loop-sender. + `run-loop-sender`.
 class run-loop-sender;
 
-1. run-loop-sender is an unspecified type such that +1. `run-loop-sender` is an unspecified type such that sender-of<run-loop-sender> is `true`. Additionally, the types reported by its `error_types` associated type is `exception_ptr`, and the value of its `sends_stopped` trait is `true`. -2. An instance of run-loop-sender remains valid until the +2. An instance of `run-loop-sender` remains valid until the end of the lifetime of its associated `run_loop` instance. -3. Let sndr be an expression of type - run-loop-sender, let rcvr be an +3. Let `sndr` be an expression of type + `run-loop-sender`, let `rcvr` be an expression such that decltype(rcvr) models the `receiver_of` concept, and let `C` be either `set_value_t` or `set_stopped_t`. Then: @@ -9284,14 +9375,14 @@ class run-loop-sender; run-loop-opstate<decay_t<decltype(rcvr)>> and is potentially-throwing if and only if the initialiation of decay_t<decltype(rcvr)> from - rcvr is potentially-throwing. + `rcvr` is potentially-throwing. * The expression get_completion_scheduler<C>(get_env(sndr)) is not potentially-throwing, has type - run-loop-scheduler, and compares equal to the - run-loop-scheduler instance from which - sndr was obtained. + `run-loop-scheduler`, and compares equal to the + `run-loop-scheduler` instance from which + `sndr` was obtained.
 template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
@@ -9299,17 +9390,17 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
 
1. run-loop-opstate<Rcvr> inherits unambiguously - from run-loop-opstate-base. + from `run-loop-opstate-base`. -2. Let o be a non-`const` lvalue of type +2. Let `o` be a non-`const` lvalue of type run-loop-opstate<Rcvr>, and let REC(o) be a non-`const` lvalue reference to an - instance of type Rcvr that was initialized with the - expression rcvr passed to the invocation of `connect` - that returned o. Then: + instance of type `Rcvr` that was initialized with the + expression `rcvr` passed to the invocation of `connect` + that returned `o`. Then: * The object to which REC(o) refers remains - valid for the lifetime of the object to which o + valid for the lifetime of the object to which `o` refers. * The type run-loop-opstate<Rcvr> overrides @@ -9338,14 +9429,14 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr> #### Constructor and destructor [exec.run.loop.ctor] #### {#spec-execution.contexts.run_loop.ctor}
-run_loop::run_loop() noexcept;
+run_loop() noexcept;
 
1. Postconditions: count is `0` and state is starting.
-run_loop::~run_loop();
+~run_loop();
 
1. Effects: If count is not `0` or if state is @@ -9354,7 +9445,7 @@ run_loop::~run_loop(); #### Member functions [exec.run.loop.members] #### {#spec-execution.contexts.run_loop.members}
-run-loop-opstate-base* run_loop::pop_front();
+run-loop-opstate-base* pop_front();
 
1. Effects: Blocks ([defns.block]) until one of the following conditions @@ -9368,7 +9459,7 @@ run_loop::~run_loop(); removed item is returned.
-void run_loop::push_back(run-loop-opstate-base* item);
+void push_back(run-loop-opstate-base* item);
 
1. Effects: Adds `item` to the back of the queue and increments @@ -9381,11 +9472,11 @@ void run_loop::push_back(run-loop-opstate-base* item); run-loop-scheduler run_loop::get_scheduler(); -1. Returns: an instance of run-loop-scheduler that +1. Returns: an instance of `run-loop-scheduler` that can be used to schedule work onto this `run_loop` instance.
-void run_loop::run();
+void run();
 
1. Effects: Equivalent to: @@ -9404,7 +9495,7 @@ void run_loop::run(); When state changes, it does so without introducing data races.
-void run_loop::finish();
+void finish();
 
1. Effects: Changes state to finishing. @@ -9421,24 +9512,26 @@ void run_loop::finish(); exposition-only entities:
-    template<class Sndr, class Env>
-      using single-sender-value-type = see below;
-
-    template<class Sndr, class Env>
-      concept single-sender =
-        sender_in<Sndr, Env> &&
-        requires { typename single-sender-value-type<Sndr, Env>; };
-
-    template<class Sndr, class Promise>
-      concept awaitable-sender =
-        single-sender<Sndr, env_of_t> &&
-        sender_to<Sndr, awaitable-receiver> && // see below
-        requires (Promise& p) {
-          { p.unhandled_stopped() } -> convertible_to<coroutine_handle<>>;
-        };
+    namespace std::execution {
+      template<class Sndr, class Env>
+        using single-sender-value-type = see below;
+
+      template<class Sndr, class Env>
+        concept single-sender =
+          sender_in<Sndr, Env> &&
+          requires { typename single-sender-value-type<Sndr, Env>; };
+
+      template<class Sndr, class Promise>
+        concept awaitable-sender =
+          single-sender<Sndr, env_of_t> &&
+          sender_to<Sndr, awaitable-receiver> && // see below
+          requires (Promise& p) {
+            { p.unhandled_stopped() } -> convertible_to<coroutine_handle<>>;
+          };
 
-    template<class Sndr, class Promise>
-      class sender-awaitable;
+      template<class Sndr, class Promise>
+        class sender-awaitable;
+    }
     
1. Alias template single-sender-value-type is defined as follows: @@ -9465,25 +9558,27 @@ void run_loop::finish(); equivalent to the following:
-        template<class Sndr, class Promise>
-        class sender-awaitable {
-          struct unit {};
-          using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>;
-          using result_t = conditional_t<is_void_v<value_t>, unit, value_t>;
-          struct awaitable-receiver;
-
-          variant<monostate, result_t, exception_ptr> result{};
-          connect_result_t<Sndr, awaitable-receiver> state;
-
-         public:
-          sender-awaitable(Sndr&& sndr, Promise& p);
-          bool await_ready() const noexcept { return false; }
-          void await_suspend(coroutine_handle<Promise>) noexcept { start(state); }
-          value_t await_resume();
-        };
+        namespace std::execution {
+          template<class Sndr, class Promise>
+          class sender-awaitable {
+            struct unit {};
+            using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>;
+            using result_t = conditional_t<is_void_v<value_t>, unit, value_t>;
+            struct awaitable-receiver;
+
+            variant<monostate, result_t, exception_ptr> result{};
+            connect_result_t<Sndr, awaitable-receiver> state;
+
+          public:
+            sender-awaitable(Sndr&& sndr, Promise& p);
+            bool await_ready() const noexcept { return false; }
+            void await_suspend(coroutine_handle<Promise>) noexcept { start(state); }
+            value_t await_resume();
+          };
+        }
         
- 1. awaitable-receiver is equivalent to the following: + 1. `awaitable-receiver` is equivalent to the following:
             struct awaitable-receiver {
@@ -9495,7 +9590,7 @@ void run_loop::finish();
             
Let `rcvr` be an rvalue expression of type - awaitable-receiver, let `crcvr` be a `const` + `awaitable-receiver`, let `crcvr` be a `const` lvalue that refers to `rcvr`, let `vs` be a parameter pack of types `Vs...`, and let `err` be an arbitrary expression of type `Err`. Then: @@ -9525,21 +9620,20 @@ void run_loop::finish(); static_cast<coroutine_handle<>>(rcvr.continuation.promise().unhandled_stopped()).resume(). 4. For any expression `tag` whose type satisfies - forwarding-query and for any pack of + `forwarding-query` and for any pack of subexpressions `as`, `get_env(crcvr).query(tag, as...)` is expression-equivalent to tag(get_env(as_const(crcvr.continuation.promise())), as...) when that expression is well-formed. - 2. sender-awaitable::sender-awaitable(Sndr&& - sndr, Promise& p) + 2. sender-awaitable(Sndr&& sndr, Promise& p) - Effects: initializes `state` with connect(std::forward<Sndr>(sndr), awaitable-receiver{&result, coroutine_handle<Promise>::from_promise(p)}). - 3. value_t sender-awaitable::await_resume() + 3. `value_t await_resume()` - Effects: equivalent to: @@ -9561,14 +9655,14 @@ void run_loop::finish(); `true`, where `A` is the type of the expression above. 2. Otherwise, `expr` if is-awaitable<Expr, U> - is `true`, where U is an unspecified class type that + is `true`, where `U` is an unspecified class type that lacks a member named `await_transform`. The condition is not is-awaitable<Expr, Promise> as that creates the potential for constraint recursion. * Preconditions: is-awaitable<Expr, Promise> is `true` and the expression `co_await expr` in a - coroutine with promise type U is + coroutine with promise type `U` is expression-equivalent to the same expression in a coroutine with promise type `Promise`. @@ -9589,30 +9683,32 @@ void run_loop::finish(); the `unhandled_stopped` of the coroutine caller's promise type is called.
-    template<class-type Promise>
-      struct with_awaitable_senders {
-        template<OtherPromise>
-          requires (!same_as<OtherPromise, void>)
-        void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
+    namespace std::execution {
+      template<class-type Promise>
+        struct with_awaitable_senders {
+          template<OtherPromise>
+            requires (!same_as<OtherPromise, void>)
+          void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
 
-        coroutine_handle<> continuation() const noexcept { return continuation; }
+          coroutine_handle<> continuation() const noexcept { return continuation; }
 
-        coroutine_handle<> unhandled_stopped() noexcept {
-          return stopped-handler(continuation.address());
-        }
+          coroutine_handle<> unhandled_stopped() noexcept {
+            return stopped-handler(continuation.address());
+          }
 
-        template<class Value>
-        see below await_transform(Value&& value);
+          template<class Value>
+          see below await_transform(Value&& value);
 
-        private:
-        // exposition only
-        [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
-          terminate();
-        }
-        coroutine_handle<> continuation{}; // exposition only
-        // exposition only
-        coroutine_handle<> (*stopped-handler)(void*) noexcept = &default_unhandled_stopped;
-      };
+          private:
+          // exposition only
+          [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
+            terminate();
+          }
+          coroutine_handle<> continuation{}; // exposition only
+          // exposition only
+          coroutine_handle<> (*stopped-handler)(void*) noexcept = &default_unhandled_stopped;
+        };
+    }
     
2. `void set_continuation(coroutine_handle h) noexcept` From e9dbf6a00d5fc5f6e6e1e9a9e05d29d3ed6a7d12 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 29 Mar 2024 11:14:19 -0700 Subject: [PATCH 48/89] rename `in_place_*` to `inplace_*`_ --- execution.bs | 153 ++++++++++++++++++++++++++++----------------------- 1 file changed, 85 insertions(+), 68 deletions(-) diff --git a/execution.bs b/execution.bs index 2ecc471..821b3c2 100644 --- a/execution.bs +++ b/execution.bs @@ -1503,20 +1503,37 @@ The changes since R8 are as follows: Fixes: - * The `tag_invoke` mechanism has been replace with member functions + * The `tag_invoke` mechanism has been replaced with member functions for customizations as per \[P2855](https://wg21.link/p2855). * Per guidance from LWG and LEWG, `receiver_adaptor` has been removed. - * The `receiver` concept is tweaked to requires that receiver types are not + * The `receiver` concept is tweaked to require that receiver types are not `final`. Without `receiver_adaptor` and `tag_invoke`, receiver adaptors are easily written using implementation inheritance. + * `std::tag_t` is made exposition-only. + + * The types `in_place_stop_token`, `in_place_stop_source`, and + `in_place_stop_callback` are renamed to `inplace_stop_token`, + `inplace_stop_source`, and `inplace_stop_callback`, respectively. + Enhancements: * The specification of the `sync_wait` algorithm has been updated for clarity. + * The specification of all the stop token, source, and callback types have + been re-expressed in terms of shared concepts. + + * Declarations are shown in their proper namespaces. + + * Editorial changes have been made to clarify what text is added, + what is removed, and what is an editorial note. + + * The section numbers of the proposed wording now match the section + numbers in the working draft of the C++ standard. + ## R8 ## {#r8} The changes since R7 are as follows: @@ -2407,8 +2424,8 @@ cancellation include: different implementation strategies. * Add `std::unstoppable_token` concept for detecting whether a `stoppable_token` can never receive a stop-request. -* Add `std::in_place_stop_token`, `std::in_place_stop_source` and - `std::in_place_stop_callback` types that provide a more efficient +* Add `std::inplace_stop_token`, `std::inplace_stop_source` and + `std::inplace_stop_callback` types that provide a more efficient implementation of a stop-token for use in structured concurrency situations. * Add `std::never_stop_token` for use in places where you never want to issue a stop-request. @@ -3968,9 +3985,9 @@ a new bullet as follows:
* when a callback invocation exits via an exception when requesting stop on a - `std::stop_source` or a `std::in_place_stop_source` ([stopsource.mem], + `std::stop_source` or a `std::inplace_stop_source` ([stopsource.mem], [stopsource.inplace.mem]), or in the constructor of `std::stop_callback` or - `std::in_place_stop_callback` ([stopcallback.cons], + `std::inplace_stop_callback` ([stopcallback.cons], [stopcallback.inplace.cons]) when a callback invocation exits via an exception. @@ -4162,8 +4179,8 @@ the new `stoppable_source` concept. The last remaining owner of the stop state automatically releases the resources associated with the stop state. -6. The types `in_place_stop_source` and `in_place_stop_token` and the class - template `in_place_stop_callback` do no dynamic memory allocation or reference +6. The types `inplace_stop_source` and `inplace_stop_token` and the class + template `inplace_stop_callback` do no dynamic memory allocation or reference counting of the stop state. They are for use when the lifetimes of the tokens and the callbacks are known to nest within the lifetime of the source. @@ -4207,15 +4224,15 @@ namespace std {
// [stoptoken.never], class never_stop_token class never_stop_token; - // [stoptoken.inplace], class in_place_stop_token - class in_place_stop_token; + // [stoptoken.inplace], class inplace_stop_token + class inplace_stop_token; - // [stopsource.inplace], class in_place_stop_source - class in_place_stop_source; + // [stopsource.inplace], class inplace_stop_source + class inplace_stop_source; - // [stopcallback.inplace], class template in_place_stop_callback + // [stopcallback.inplace], class template inplace_stop_callback template<class Callback> - class in_place_stop_callback; + class inplace_stop_callback; template<class T, class Callback> using stop_callback_for_t = T::template callback_type<Callback>;
@@ -4961,36 +4978,36 @@ explicit stop_callback(stop_token&& st, C&& cb)
-Insert a new subclause, Class `in_place_stop_token` +Insert a new subclause, Class `inplace_stop_token` [stoptoken.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].
-### Class `in_place_stop_token` [stoptoken.inplace] ### {#spec-stoptoken.inplace} +### Class `inplace_stop_token` [stoptoken.inplace] ### {#spec-stoptoken.inplace} #### General [stoptoken.inplace.general] #### {#spec-stoptoken.inplace.general} -1. The class `in_place_stop_token` models the concept `stoppable_token`. It - references the stop state of its associated `in_place_stop_source` object +1. The class `inplace_stop_token` models the concept `stoppable_token`. It + references the stop state of its associated `inplace_stop_source` object ([stopsource.inplace]), if any.
     namespace std {
-      class in_place_stop_token {
+      class inplace_stop_token {
       public:
         template<class CB>
-          using callback_type = in_place_stop_callback<CB>;
+          using callback_type = inplace_stop_callback<CB>;
 
-        in_place_stop_token() noexcept = default;
-        bool operator==(const in_place_stop_token&) const noexcept = default;
+        inplace_stop_token() noexcept = default;
+        bool operator==(const inplace_stop_token&) const noexcept = default;
 
         // [stoptoken.inplace.mem], member functions
         bool stop_requested() const noexcept;
         bool stop_possible() const noexcept;
-        void swap(in_place_stop_token&) noexcept;
+        void swap(inplace_stop_token&) noexcept;
 
       private:
-        const in_place_stop_source* stop-source = nullptr; // exposition only
+        const inplace_stop_source* stop-source = nullptr; // exposition only
       };
     }
     
@@ -4998,7 +5015,7 @@ of Stop tokens [thread.stoptoken]. #### Member functions [stoptoken.inplace.members] #### {#spec-stoptoken.inplace.members}
-void swap(in_place_stop_token& rhs) noexcept;
+void swap(inplace_stop_token& rhs) noexcept;
 
1. *Effects*: Exchanges the values of `stop-source` and @@ -5013,7 +5030,7 @@ bool stop_requested() const noexcept; 2. As specified in [basic.life], the behavior of `stop_requested()` is undefined unless the call strongly happens before the - start of the destructor of the associated `in_place_stop_source`, if + start of the destructor of the associated `inplace_stop_source`, if any.
@@ -5025,41 +5042,41 @@ bool stop_possible() const noexcept;
 4. As specified in [basic.stc.general], the behavior of
     `stop_possible()` is implementation-defined unless the call strongly happens
     before the end of the storage duration of the associated
-    `in_place_stop_source` object, if any.
+    `inplace_stop_source` object, if any.
 
 
-Insert a new subclause, Class `in_place_stop_source` +Insert a new subclause, Class `inplace_stop_source` [stopsource.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].
-### Class `in_place_stop_source` [stopsource.inplace] ### {#spec-stopsource.inplace} +### Class `inplace_stop_source` [stopsource.inplace] ### {#spec-stopsource.inplace} #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general} -1. The class `in_place_stop_source` models `stoppable_source`. Unlike - `stop_source`, `in_place_stop_source` does not require dynamic allocation or +1. The class `inplace_stop_source` models `stoppable_source`. Unlike + `stop_source`, `inplace_stop_source` does not require dynamic allocation or reference counting of a shared stop state. Instead, it requires that all - uses of associated `in_place_stop_token` and `in_place_stop_callback` - objects happen before the `in_place_stop_source` is destroyed. + uses of associated `inplace_stop_token` and `inplace_stop_callback` + objects happen before the `inplace_stop_source` is destroyed.
     namespace std {
-      class in_place_stop_source {
+      class inplace_stop_source {
       public:
         // [stopsource.inplace.cons], constructors, copy, and assignment
-        in_place_stop_source() noexcept;
+        inplace_stop_source() noexcept;
 
-        in_place_stop_source(in_place_stop_source&&) = delete;
-        in_place_stop_source(const in_place_stop_source&) = delete;
-        in_place_stop_source& operator=(in_place_stop_source&&) = delete;
-        in_place_stop_source& operator=(const in_place_stop_source&) = delete;
-        ~in_place_stop_source();
+        inplace_stop_source(inplace_stop_source&&) = delete;
+        inplace_stop_source(const inplace_stop_source&) = delete;
+        inplace_stop_source& operator=(inplace_stop_source&&) = delete;
+        inplace_stop_source& operator=(const inplace_stop_source&) = delete;
+        ~inplace_stop_source();
 
         //[stopsource.inplace.mem], stop handling
-        in_place_stop_token get_token() const noexcept;
+        inplace_stop_token get_token() const noexcept;
         static constexpr bool stop_possible() noexcept { return true; }
         bool stop_requested() const noexcept;
         bool request_stop() noexcept;
@@ -5070,7 +5087,7 @@ of Stop tokens [thread.stoptoken].
 #### Constructors, copy, and assignment [stopsource.inplace.cons] #### {#spec-stopsource.inplace.cons}
 
 
-in_place_stop_source() noexcept;
+inplace_stop_source() noexcept;
 
1. *Effects*: Initializes a new stop state inside `*this`. @@ -5080,10 +5097,10 @@ in_place_stop_source() noexcept; #### Members [stopsource.inplace.mem] #### {#spec-stopsource.inplace.mem}
-in_place_stop_token get_token() const noexcept;
+inplace_stop_token get_token() const noexcept;
 
-1. *Returns*: A new associated `in_place_stop_token` object. +1. *Returns*: A new associated `inplace_stop_token` object.
 bool stop_requested() const noexcept;
@@ -5104,12 +5121,12 @@ bool request_stop() noexcept;
 
Insert a new subclause, Class template -`in_place_stop_callback` [stopcallback.inplace], after the subclause +`inplace_stop_callback` [stopcallback.inplace], after the subclause added above, as a new subclause of Stop tokens [thread.stoptoken].
-### Class template `in_place_stop_callback` [stopcallback.inplace] ### {#spec-stopcallback.inplace} +### Class template `inplace_stop_callback` [stopcallback.inplace] ### {#spec-stopcallback.inplace} #### General [stopcallback.inplace.general] #### {#spec-stopcallback.inplace.general} @@ -5118,52 +5135,52 @@ added above, as a new subclause of Stop tokens [thread.stoptoken].
     namespace std {
       template<class Callback>
-      class in_place_stop_callback {
+      class inplace_stop_callback {
       public:
         using callback_type = Callback;
 
         // [stopcallback.inplace.cons], constructors and destructor
         template<class C>
-          explicit in_place_stop_callback(in_place_stop_token st, C&& cb)
+          explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
             noexcept(is_nothrow_constructible_v<Callback, C>);
-        ~in_place_stop_callback();
+        ~inplace_stop_callback();
 
-        in_place_stop_callback(in_place_stop_callback&&) = delete;
-        in_place_stop_callback(const in_place_stop_callback&) = delete;
-        in_place_stop_callback& operator=(in_place_stop_callback&&) = delete;
-        in_place_stop_callback& operator=(const in_place_stop_callback&) = delete;
+        inplace_stop_callback(inplace_stop_callback&&) = delete;
+        inplace_stop_callback(const inplace_stop_callback&) = delete;
+        inplace_stop_callback& operator=(inplace_stop_callback&&) = delete;
+        inplace_stop_callback& operator=(const inplace_stop_callback&) = delete;
 
       private:
         Callback stop-callback;      // exposition only
       };
 
       template<class Callback>
-        in_place_stop_callback(in_place_stop_token, Callback)
-          -> in_place_stop_callback<Callback>;
+        inplace_stop_callback(inplace_stop_token, Callback)
+          -> inplace_stop_callback<Callback>;
     }
     
-1. *Mandates*: `in_place_stop_callback` is instantiated with an argument for the +1. *Mandates*: `inplace_stop_callback` is instantiated with an argument for the template parameter `Callback` that satisfies both `invocable` and `destructible`. -2. *Remarks:* For a type `C`, if `stoppable_callback_for` is satisfied, then `stoppable_callback_for` is modeled. The exposition-only + inplace_stop_token, C>` is modeled. The exposition-only `stop-callback` member is the associated callback function - ([stoptoken.concepts]) of `in_place_stop_callback` objects. + ([stoptoken.concepts]) of `inplace_stop_callback` objects. Implementations are not permitted to use additional storage, such as dynamic memory, to store the state necessary for an - `in_place_stop_callback`'s association with an `in_place_stop_source` object + `inplace_stop_callback`'s association with an `inplace_stop_source` object or to register the callback invocation with the associated - `in_place_stop_source` object. + `inplace_stop_source` object. #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons}
 template<class C>
-  explicit in_place_stop_callback(in_place_stop_token st, C&& cb)
+  explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
     noexcept(is_nothrow_constructible_v<Callback, C>);
 
@@ -5174,7 +5191,7 @@ template<class C> ([stoptoken.concepts]).
-~in_place_stop_callback();
+~inplace_stop_callback();
 
6. *Effects*: Executes a stoppable callback deregistration @@ -6437,7 +6454,7 @@ namespace std::execution { 12.
         struct on-stop-request { // exposition only
-          in_place_stop_source& stop-src; // exposition only
+          inplace_stop_source& stop-src; // exposition only
           void operator()() noexcept { stop-src.request_stop(); }
         };
         
@@ -7994,7 +8011,7 @@ namespace std::execution { 2. Let `shared-env` be the type of an environment such that, given an instance `env`, the expression `get_stop_token(env)` is well-formed - and has type `in_place_stop_token`. + and has type `inplace_stop_token`. 3. The names `split` and `ensure_started` denote customization point objects. Let the expression `shared-cpo` be one of `split` or @@ -8144,7 +8161,7 @@ namespace std::execution { struct env { // exposition only shared-state<Sndr>* sh-state; // exposition only - in_place_stop_source query(get_stop_token_t) const noexcept { + inplace_stop_source query(get_stop_token_t) const noexcept { return sh-state->stop_src.get_token(); } }; @@ -8177,7 +8194,7 @@ namespace std::execution { void inc-ref() noexcept; void dec-ref() noexcept; - in_place_stop_source stop_src{}; + inplace_stop_source stop_src{}; variant-type result{}; state-list-type waiting_states; state-flag-type completed; @@ -8481,7 +8498,7 @@ namespace std::execution { void complete(Rcvr& rcvr) noexcept; // see below atomic<size_t> count{sizeof...(sndrs)}; - in_place_stop_source stop_src{}; + inplace_stop_source stop_src{}; atomic<disposition> disp{disposition::started}; errors_variant errors{}; values_tuple values{}; From 6d891d1e657422bbf8e1f11650ba51704450e930 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 29 Mar 2024 11:25:11 -0700 Subject: [PATCH 49/89] remove the word "shared" from the stop token concepts specification --- execution.bs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/execution.bs b/execution.bs index 821b3c2..3bfe66a 100644 --- a/execution.bs +++ b/execution.bs @@ -4266,7 +4266,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class 2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the - same logical shared stop state; let `init` be an object of type + same logical stop state; let `init` be an object of type `Initializer`; and let `CB` denote the type `stop_callback_for_t`. @@ -4328,7 +4328,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class deregistration shall have no effect. 2. Otherwise, the invocation of `callback` shall be removed from - the shared stop state. + the associated stop state. 3. If `callback` is currently being invoked on another thread then the stoppable callback deregistration shall block @@ -4343,7 +4343,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class 5. A stoppable callback deregistration shall not block on the completion of the invocation of some other callback registered with the same - shared stop state. + logical stop state. 6. As a final step, the stoppable callback deregistration shall destroy the callback function. From 1685da6b3bf1a70dda323b353cb5b337a7e52917 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 29 Mar 2024 11:47:36 -0700 Subject: [PATCH 50/89] add some missing `// exposition only` annotations --- execution.bs | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/execution.bs b/execution.bs index 3bfe66a..b3513ae 100644 --- a/execution.bs +++ b/execution.bs @@ -7216,7 +7216,7 @@ namespace std::execution { struct awaiter { decltype(fn) fn; - static bool await_ready() noexcept { return false; } + static constexpr bool await_ready() noexcept { return false; } void await_suspend(coroutine_handle<>) noexcept { fn(); } [[noreturn]] void await_resume() noexcept { unreachable(); } }; @@ -9578,19 +9578,21 @@ void finish(); namespace std::execution { template<class Sndr, class Promise> class sender-awaitable { - struct unit {}; - using value_t = single-sender-value-type<Sndr, env_of_t<Promise>>; - using result_t = conditional_t<is_void_v<value_t>, unit, value_t>; - struct awaitable-receiver; + struct unit {}; // exposition only + using value-type = // exposition only + single-sender-value-type<Sndr, env_of_t<Promise>>; + using result-type = // exposition only + conditional_t<is_void_v<value-type>, unit, value-type>; + struct awaitable-receiver; // exposition only - variant<monostate, result_t, exception_ptr> result{}; - connect_result_t<Sndr, awaitable-receiver> state; + variant<monostate, result-type, exception_ptr> result{}; // exposition only + connect_result_t<Sndr, awaitable-receiver> state; // exposition only public: sender-awaitable(Sndr&& sndr, Promise& p); - bool await_ready() const noexcept { return false; } + static constexpr bool await_ready() noexcept { return false; } void await_suspend(coroutine_handle<Promise>) noexcept { start(state); } - value_t await_resume(); + value-type await_resume(); }; } @@ -9600,8 +9602,8 @@ void finish();
             struct awaitable-receiver {
               using receiver_concept = receiver_t;
-              variant<monostate, result_t, exception_ptr>* result-ptr;
-              coroutine_handle<Promise> continuation;
+              variant<monostate, result-type, exception_ptr>* result-ptr; // exposition only
+              coroutine_handle<Promise> continuation;                     // exposition only
               // ... see below
             };
             
@@ -9612,8 +9614,9 @@ void finish(); `Vs...`, and let `err` be an arbitrary expression of type `Err`. Then: - 1. If `constructible_from` is satisfied, the - expression `set_value(rcvr, vs...)` is equivalent to: + 1. If constructible_from<result-type, Vs...> + is satisfied, the expression `set_value(rcvr, vs...)` is + equivalent to:
                 try {
@@ -9643,22 +9646,22 @@ void finish();
                 tag(get_env(as_const(crcvr.continuation.promise())),
                 as...) when that expression is well-formed.
 
-        2. sender-awaitable(Sndr&& sndr, Promise& p)
+        2. sender-awaitable(Sndr&& sndr, Promise& p)
 
             - Effects: initializes `state` with
                 connect(std::forward<Sndr>(sndr),
                 awaitable-receiver{&result,
                 coroutine_handle<Promise>::from_promise(p)}).
 
-        3. `value_t await_resume()`
+        3. value-type await_resume()
 
             - Effects: equivalent to:
 
                 
                 if (result.index() == 2)
                   rethrow_exception(get<2>(result));
-                if constexpr (!is_void_v<value_t>)
-                  return std::forward<value_t>(get<1>(result));
+                if constexpr (!is_void_v<value-type>)
+                  return std::forward<value-type>(get<1>(result));
                 
2. `as_awaitable` is a customization point object. For some subexpressions From ff4e56286cea80b30759f832ffa8f886cb9664c9 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 29 Mar 2024 16:22:16 -0700 Subject: [PATCH 51/89] replace some uses of the no-longer-extant `tag_t` --- execution.bs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/execution.bs b/execution.bs index b3513ae..3515da1 100644 --- a/execution.bs +++ b/execution.bs @@ -7842,7 +7842,7 @@ namespace std::execution { }
- 2. impls-for<tag_t<let-cpo>>::get-state is + 2. impls-for<decayed-typeof<let-cpo>>::get-state is is initialized with a callable object equivalent to the following:
@@ -7867,7 +7867,7 @@ namespace std::execution {
                 specialization named by
                 completion_signatures_of_t<child-type<Sndr>,
                 env_of_t<Rcvr>>. Let `LetSigs` be a pack of those types in `Sigs`
-                with a return type of tag_t<set-cpo>. Let
+                with a return type of decayed-typeof<set-cpo>. Let
                 `as-tuple` be an alias template such that
                 as-tuple<Tag(Args...)> denotes the type
                 decayed-tuple<Args...>. Then
@@ -7897,13 +7897,13 @@ namespace std::execution {
             start(op2);
             
- 4. impls-for<tag_t<let-cpo>>::complete is + 4. impls-for<decayed-typeof<let-cpo>>::complete is is initialized with a callable object equivalent to the following:
             []<class Tag, class... Args>
               (auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
-                if constexpr (same_as<Tag, tag_t<set-cpo>>) {
+                if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
                   TRY-EVAL(std::move(rcvr), let-bind(state, rcvr, std::forward<Args>(args)...));
                 } else {
                   Tag()(std::move(rcvr), std::forward<Args>(args)...);
@@ -7912,7 +7912,7 @@ namespace std::execution {
             
6. Let `sndr` and `env` be subexpressions, and let `Sndr` be `decltype((sndr))`. - If sender-for<Sndr, tag_t<let-cpo>> is + If sender-for<Sndr, decayed-typeof<let-cpo>> is `false`, then the expression let-cpo.transform_env(sndr, env) is ill-formed. Otherwise, it is equal to JOIN-ENV(let-env(sndr), FWD-ENV(env)). From ffae82f6dcb22d0168434a571a57b4bd9151b42e Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 2 Apr 2024 10:42:47 -0700 Subject: [PATCH 52/89] make `stoppable_source` and `stoppable_callback_for` exposition-only --- execution.bs | 189 ++++++++++++++++++++++++++------------------------- 1 file changed, 95 insertions(+), 94 deletions(-) diff --git a/execution.bs b/execution.bs index 3515da1..cca5487 100644 --- a/execution.bs +++ b/execution.bs @@ -2419,9 +2419,9 @@ first proposed in [[P2175R0]]. At a high-level, the facilities proposed by this paper for supporting cancellation include: -* Add `std::stoppable_token` and `std::stoppable_token_for` concepts that - generalise the interface of `std::stop_token` type to allow other types with - different implementation strategies. +* Add a `std::stoppable_token` concept that generalises the interface of the + `std::stop_token` type to allow other stop token types with different + implementation strategies. * Add `std::unstoppable_token` concept for detecting whether a `stoppable_token` can never receive a stop-request. * Add `std::inplace_stop_token`, `std::inplace_stop_source` and @@ -4120,21 +4120,20 @@ namespace std { typically because the result is no longer required. Such a request is called a stop request. -2. stoppable_source, - stoppable_token, and - stoppable_callback_for - implementare concepts that specify the required syntax - and semantics of shared ownershipaccess of a - stop state. Any - stoppable_source, - stoppable_token, or - stoppable_callback_for object that - shares ownership ofrefers to the same stop state is an - associated stoppable_source, - stoppable_token, or - stoppable_callback_for, respectively. - The last remaining owner of the stop state automatically releases the - resources associated with the stop state. +2. `stop_source`, `stop_token`, and `stop_callback` implement + `stoppable-source`, `stoppable_token`, and + `stoppable-callback-for` are concepts that specify the required + syntax and semantics of shared ownershipaccess + of a stop state. Any `stop_source`, + `stop_token`, or `stop_callback` object that shares ownership of the same + stop state is an **associated** `stop_source`, `stop_token`, or + `stop_callback`, respectively. Any object modeling + `stoppable-source`, `stoppable_token`, or + `stoppable-callback-for` that refers to the same stop state is an + associated `stoppable-source`, + `stoppable_token`, or `stoppable-callback-for`, + respectively. The last remaining owner of the stop state + automatically releases the resources associated with the stop state. 3. A stoppable_token can be passed to an operation whichthat can either @@ -4147,28 +4146,27 @@ namespace std { template whichthat will be called in the event that a stop request is made.
- A stop request made via a stoppable_source will be - visible to all associated stoppable_token and - stoppable_source objects. Once a stop request has - been made it cannot be withdrawn (a subsequent stop request has no effect). + A stop request made via a `stop_source`an object that models + `stoppable-source` will be visible to all associated + stoppable_token and `stop_source` + `stoppable-source` objects. Once a stop request has been + made it cannot be withdrawn (a subsequent stop request has no effect). -4. Callbacks registered via a - stoppable_callback_for object are called - when a stop request is first made by any associated - stoppable_source object. +4. Callbacks registered via a `stop_callback` objectan object + that models `stoppable-callback-for` are called when a stop + request is first made by any associated `stop_source` + `stoppable-source` object. The following paragraph is moved to the specification of -the new `stoppable_source` concept. +the new `stoppable-source` concept.
5. Calls to the functions `request_stop`, `stop_requested`, and `stop_possible` do not introduce data races. A call to `request_stop` that returns `true` - synchronizes with a call to `stop_requested` on an associated - stoppable_token or - stoppable_source object that returns `true`. - Registration of a callback synchronizes with the invocation of that - callback. + synchronizes with a call to `stop_requested` on an associated `stop_token` + or `stop_source` object that returns `true`. Registration of a callback + synchronizes with the invocation of that callback.
@@ -4195,7 +4193,7 @@ declarations into the `` synopsis: namespace std {
// [stoptoken.concepts], stop token concepts template<class Callback, class Token, class Initializer = Callback> - concept stoppable_callback_for = see below; + concept stoppable-callback-for = see below; // exposition only template<class Token> concept stoppable_token = see below; @@ -4204,7 +4202,7 @@ namespace std { concept unstoppable_token = see below; template<class Source> - concept stoppable_source = see below;
+ concept stoppable-source = see below; // exposition only
// 33.3.3, class stop_token class stop_token; @@ -4253,12 +4251,12 @@ Header `` synopsis [thread.stoptoken.syn] and Class arguments, if the type `stop_callback_for_t` is valid, it denotes the type of a stop callback to use to register a callback to be executed if a stop request is ever made on the `stoppable_token`'s - associated stop source. The `stoppable_callback_for` concept checks for a - callback compatible with a given stop token type. + associated stop source. The exposition-only `stoppable-callback-for` + concept checks for a callback compatible with a given stop token type.
     template<class Callback, class Token, class Initializer = Callback>
-      concept stoppable_callback_for =
+      concept stoppable-callback-for = // exposition only
         invocable<Callback> &&
         constructible_from<Callback, Initializer> &&
         requires { typename stop_callback_for_t<Token, Callback>; } &&
@@ -4270,8 +4268,8 @@ Header `` synopsis [thread.stoptoken.syn] and Class
     `Initializer`; and let `CB` denote the type `stop_callback_for_t`.
 
-3. The concept `stoppable_callback_for` is modeled
-    only if:
+3. The concept stoppable-callback-for<Callback, Token,
+    Initializer> is modeled only if:
 
     1. The following concepts are modeled:
 
@@ -4390,27 +4388,29 @@ Header `` synopsis [thread.stoptoken.syn] and Class
         after `E` shall evaluate to `true`.
 
     3. For any types `Callback` and `Initializer`, if
-        `stoppable_callback_for` is satisfied,
-        then `stoppable_callback_for` shall be
-        modeled.
-
-    4. A `stoppable_token` object has at most one associated logical stop state.
-        A `stoppable_token` object with no associated stop state is said to be
-        disengaged. For a disengaged `stoppable_token`
-        object, `stop_possible` and `stop_requested` shall return `false`. If
-        `t` and `u` reference the same stop state, or if both `t` and `u` are
-        disengaged, `t == u` shall be `true`; otherwise, it shall be `false`.
-
-6. A model of `stoppable_source` can be queried whether stop has been requested
-    (`stop_requested`) and whether stop is possible (`stop_possible`). It is a
-    factory for associated stop tokens (`get_token`) and can be explicitly
-    placed into the "stop requested" state (`request_stop`). It maintains a list
-    of registered stop callback invocations that it executes when a stop request
-    is first made.
+        stoppable-callback-for<Callback, Token,
+        Initializer> is satisfied, then
+        stoppable-callback-for<Callback, Token,
+        Initializer> shall be modeled.
+
+    4. An object that models `stoppable_token` has at most one associated
+        logical stop state. A `stoppable_token` object with no associated stop
+        state is said to be disengaged. For a disengaged
+        `stoppable_token` object, `stop_possible` and `stop_requested` shall
+        return `false`. If `t` and `u` reference the same stop state, or if both
+        `t` and `u` are disengaged, `t == u` shall be `true`; otherwise, it
+        shall be `false`.
+
+6. A model of the exposition-only `stoppable-source` concept can be
+    queried whether stop has been requested (`stop_requested`) and whether stop
+    is possible (`stop_possible`). It is a factory for associated stop tokens
+    (`get_token`) and can be explicitly placed into the "stop requested" state
+    (`request_stop`). It maintains a list of registered stop callback
+    invocations that it executes when a stop request is first made.
 
     
     template<class Source>
-      concept stoppable_source =
+      concept stoppable-source = // exposition only
         requires (Source& src, const Source csrc) { // see implicit expression variations
                                                     // ([concepts.equality])
           { csrc.get_token() } -> stoppable_token;
@@ -4420,14 +4420,15 @@ Header `` synopsis [thread.stoptoken.syn] and Class
         };
     
- 1. A `stoppable_source` object has at most one associated logical stop - state. A `stoppable_source` object with no associated stop state is said - to be disengaged. For a disengaged `stoppable_source` object, - `stop_possible` and `stop_requested` shall return `false`. + 1. A `stoppable-source` object has at most one associated logical + stop state. A `stoppable-source` object with no associated stop + state is said to be disengaged. For a disengaged + `stoppable-source` object, `stop_possible` and `stop_requested` + shall return `false`. - 2. A disengaged `stoppable_source` object shall return a disengaged stop token - from `get_token()`. Otherwise, `get_token()` shall return a stop token that - is associated with the stop state of the source. + 2. A disengaged `stoppable-source` object shall return a disengaged + stop token from `get_token()`. Otherwise, `get_token()` shall return a + stop token that is associated with the stop state of the source. The following paragraph is moved from the introduction, with minor modifications (underlined in green). @@ -4437,16 +4438,15 @@ Header `` synopsis [thread.stoptoken.syn] and Class functions on associated `stoppable_token` objects do not introduce data races. A call to `request_stop` that returns `true` synchronizes with a call to `stop_requested` on an associated - stoppable_token or - stoppable_source object that returns `true`. - Registration of a callback synchronizes with the invocation of that - callback. + stoppable_token or `stop_source` + `stoppable-source` object that returns `true`. Registration + of a callback synchronizes with the invocation of that callback. The following paragraph is taken from [[#spec-stopsource.mem]] and modified. - 4. If the `stoppable_source` is disengaged, `request_stop` shall have no - effect and return `false`. Otherwise, it shall execute a `stoppable-source` is disengaged, `request_stop` shall have + no effect and return `false`. Otherwise, it shall execute a stop request operation on the associated stop state. A stop request operation determines whether the stop state has received a stop request, and if not, makes a stop request. The determination and @@ -4638,7 +4638,7 @@ friend void swap(stop_token& x, stop_token& y) noexcept; request. A stop request made on a `stop_source` object is visible to all associated `stop_source` and `stop_token` ([thread.stoptoken]) objects. Once a stop request has been made it cannot be withdrawn (a subsequent stop - request has no effect)models `stoppable_source`. + request has no effect)models `stoppable-source`.
 namespace std {
@@ -4881,10 +4881,12 @@ namespace std {
 
 
-3. *Remarks:* For a type `C`, if `stoppable_callback_for` is satisfied, then `stoppable_callback_for` is - modeled. The exposition-only `callback` member is the associated callback - function ([stoptoken.concepts]) of `stop_callback` objects. +3. *Remarks:* For a type `C`, if + stoppable-callback-for<Callback, stop_token, C> is + satisfied, then stoppable-callback-for<Callback, stop_token, + C> is modeled. The exposition-only `callback` member is the + associated callback function ([stoptoken.concepts]) of + `stop_callback` objects.
@@ -5056,7 +5058,7 @@ of Stop tokens [thread.stoptoken]. #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general} -1. The class `inplace_stop_source` models `stoppable_source`. Unlike +1. The class `inplace_stop_source` models `stoppable-source`. Unlike `stop_source`, `inplace_stop_source` does not require dynamic allocation or reference counting of a shared stop state. Instead, it requires that all uses of associated `inplace_stop_token` and `inplace_stop_callback` @@ -5164,11 +5166,13 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. template parameter `Callback` that satisfies both `invocable` and `destructible`. -2. *Remarks:* For a type `C`, if `stoppable_callback_for` is satisfied, then `stoppable_callback_for` is modeled. The exposition-only - `stop-callback` member is the associated callback function - ([stoptoken.concepts]) of `inplace_stop_callback` objects. +2. *Remarks:* For a type `C`, if + stoppable-callback-for<Callback, inplace_stop_token, + C> is satisfied, then + stoppable-callback-for<Callback, inplace_stop_token, + C> is modeled. The exposition-only `stop-callback` member is + the associated callback function ([stoptoken.concepts]) of + `inplace_stop_callback` objects. Implementations are not permitted to use additional storage, such as dynamic memory, to store the state necessary for an @@ -6533,30 +6537,27 @@ namespace std::execution { template<class Sndr, class Rcvr, class Index> requires well-formed<env-type, Index, Sndr, Rcvr> struct basic-receiver { // exposition only - using tag-type = tag_of_t<Sndr>; // exposition only using receiver_concept = receiver_t; + using tag-type = tag_of_t<Sndr>; // exposition only + using state-type = state-type<Sndr, Rcvr>; // exposition only + static constexpr const auto& complete = impls-for<tag-type>::complete; // exposition only + template<class... Args> - requires cpo-callable<impls-for<tag-type>::complete, - Index, state-type<Sndr, Rcvr>&, Rcvr&, set_value_t, Args...> + requires cpo-callable<complete, Index, state-type&, Rcvr&, set_value_t, Args...> void set_value(Args&&... args) && noexcept { - (void) impls-for<tag-type>::complete( - Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...); + complete(Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...); } template<class Error> - requires cpo-callable<impls-for<tag-type>::complete, - Index, state-type<Sndr, Rcvr>&, Rcvr&, set_error_t, Error> + requires cpo-callable<complete, Index, state-type&, Rcvr&, set_error_t, Error> void set_error(Error&& err) && noexcept { - (void) impls-for<tag-type>::complete( - Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err)); + complete(Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err)); } void set_stopped() && noexcept - requires cpo-callable<impls-for<tag-type>::complete, - Index, state-type<Sndr, Rcvr>&, Rcvr&, set_stopped_t> { - (void) impls-for<tag-type>::complete( - Index(), op->state, op->rcvr, set_stopped_t()); + requires cpo-callable<complete, Index, state-type&, Rcvr&, set_stopped_t> { + complete(Index(), op->state, op->rcvr, set_stopped_t()); } auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> { From c498d8d164590fa43bc10d0f4b4de7b39b9190d2 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 2 Apr 2024 10:57:59 -0700 Subject: [PATCH 53/89] R9 --- P2300R9.html | 11641 +++++++++++++++++++++++++++++++++++++++++++++++++ execution.bs | 4 +- 2 files changed, 11643 insertions(+), 2 deletions(-) create mode 100644 P2300R9.html diff --git a/P2300R9.html b/P2300R9.html new file mode 100644 index 0000000..09f71a3 --- /dev/null +++ b/P2300R9.html @@ -0,0 +1,11641 @@ + + + + + P2300R9: `std::execution` + + + + + + + + + + + + + + + + + +
+

+

P2300R9
std::execution

+

Published Proposal,

+
+
+
Authors: +
+
+
+
+
+
+
+
+
+
Source: +
GitHub +
Issue Tracking: +
GitHub +
Project: +
ISO/IEC 14882 Programming Languages — C++, ISO/IEC JTC1/SC22/WG21 +
Audience: +
SG1, LEWG +
+
+
+
+
+ +
+

1. Introduction

+

This paper proposes a self-contained design for a Standard C++ framework for +managing asynchronous execution on generic execution resources. It is based on +the ideas in A Unified Executors Proposal for C++ and its companion papers.

+

1.1. Motivation

+

Today, C++ software is increasingly asynchronous and parallel, a trend that is +likely to only continue going forward. Asynchrony and parallelism appears +everywhere, from processor hardware interfaces, to networking, to file I/O, to +GUIs, to accelerators. Every C++ domain and every platform needs to deal with +asynchrony and parallelism, from scientific computing to video games to +financial services, from the smallest mobile devices to your laptop to GPUs in +the world’s fastest supercomputer.

+

While the C++ Standard Library has a rich set of concurrency primitives +(std::atomic, std::mutex, std::counting_semaphore, etc) and lower level +building blocks (std::thread, etc), we lack a Standard vocabulary and +framework for asynchrony and parallelism that C++ programmers desperately need. std::async/std::future/std::promise, C++11’s intended exposure for +asynchrony, is inefficient, hard to use correctly, and severely lacking in +genericity, making it unusable in many contexts. We introduced parallel +algorithms to the C++ Standard Library in C++17, and while they are an excellent +start, they are all inherently synchronous and not composable.

+

This paper proposes a Standard C++ model for asynchrony based around three key +abstractions: schedulers, senders, and receivers, and a set of customizable +asynchronous algorithms.

+

1.2. Priorities

+
    +
  • +

    Be composable and generic, allowing users to write code that can be used with +many different types of execution resources.

    +
  • +

    Encapsulate common asynchronous patterns in customizable and reusable +algorithms, so users don’t have to invent things themselves.

    +
  • +

    Make it easy to be correct by construction.

    +
  • +

    Support the diversity of execution resources and execution agents, because not +all execution agents are created equal; some are less capable than others, +but not less important.

    +
  • +

    Allow everything to be customized by an execution resource, including transfer +to other execution resources, but don’t require that execution resources +customize everything.

    +
  • +

    Care about all reasonable use cases, domains and platforms.

    +
  • +

    Errors must be propagated, but error handling must not present a burden.

    +
  • +

    Support cancellation, which is not an error.

    +
  • +

    Have clear and concise answers for where things execute.

    +
  • +

    Be able to manage and terminate the lifetimes of objects asynchronously.

    +
+

1.3. Examples: End User

+

In this section we demonstrate the end-user experience of asynchronous +programming directly with the sender algorithms presented in this paper. See § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers for short explanations of the algorithms used in +these code examples.

+

1.3.1. Hello world

+
using namespace std::execution;
+
+scheduler auto sch = thread_pool.scheduler();                                 // 1
+
+sender auto begin = schedule(sch);                                            // 2
+sender auto hi = then(begin, []{                                              // 3
+    std::cout << "Hello world! Have an int.";                                 // 3
+    return 13;                                                                // 3
+});                                                                           // 3
+sender auto add_42 = then(hi, [](int arg) { return arg + 42; });              // 4
+
+auto [i] = this_thread::sync_wait(add_42).value();                            // 5
+
+

This example demonstrates the basics of schedulers, senders, and receivers:

+
    +
  1. +

    First we need to get a scheduler from somewhere, such as a thread pool. A +scheduler is a lightweight handle to an execution resource.

    +
  2. +

    To start a chain of work on a scheduler, we call § 4.19.1 execution::schedule, which returns a sender that completes on +the scheduler. A sender describes asynchronous work and sends a signal +(value, error, or stopped) to some recipient(s) when that work completes.

    +
  3. +

    We use sender algorithms to produce senders and compose asynchronous work. § 4.20.2 execution::then is a sender adaptor that takes an input +sender and a std::invocable, and calls the std::invocable on the signal +sent by the input sender. The sender returned by then sends the result of +that invocation. In this case, the input sender came from schedule, so its void, meaning it won’t send us a value, so our std::invocable takes no +parameters. But we return an int, which will be sent to the next recipient.

    +
  4. +

    Now, we add another operation to the chain, again using § 4.20.2 execution::then. This time, we get sent a value - the int from the previous step. We add 42 to it, and then return the result.

    +
  5. +

    Finally, we’re ready to submit the entire asynchronous pipeline and wait for +its completion. Everything up until this point has been completely +asynchronous; the work may not have even started yet. To ensure the work has +started and then block pending its completion, we use § 4.21.2 this_thread::sync_wait, which will either return a std::optional<std::tuple<...>> with the value sent by the last sender, or +an empty std::optional if the last sender sent a stopped signal, or it +throws an exception if the last sender sent an error.

    +
+

1.3.2. Asynchronous inclusive scan

+
using namespace std::execution;
+
+sender auto async_inclusive_scan(scheduler auto sch,                          // 2
+                                 std::span<const double> input,               // 1
+                                 std::span<double> output,                    // 1
+                                 double init,                                 // 1
+                                 std::size_t tile_count)                      // 3
+{
+  std::size_t const tile_size = (input.size() + tile_count - 1) / tile_count;
+
+  std::vector<double> partials(tile_count + 1);                               // 4
+  partials[0] = init;                                                         // 4
+
+  return just(std::move(partials))                                            // 5
+       | transfer(sch)
+       | bulk(tile_count,                                                     // 6
+           [ = ](std::size_t i, std::vector<double>& partials) {              // 7
+             auto start = i * tile_size;                                      // 8
+             auto end   = std::min(input.size(), (i + 1) * tile_size);        // 8
+             partials[i + 1] = *--std::inclusive_scan(begin(input) + start,   // 9
+                                                      begin(input) + end,     // 9
+                                                      begin(output) + start); // 9
+           })                                                                 // 10
+       | then(                                                                // 11
+           [](std::vector<double>&& partials) {
+             std::inclusive_scan(begin(partials), end(partials),              // 12
+                                 begin(partials));                            // 12
+             return std::move(partials);                                      // 13
+           })
+       | bulk(tile_count,                                                     // 14
+           [ = ](std::size_t i, std::vector<double>& partials) {              // 14
+             auto start = i * tile_size;                                      // 14
+             auto end   = std::min(input.size(), (i + 1) * tile_size);        // 14
+             std::for_each(begin(output) + start, begin(output) + end,        // 14
+               [&] (double& e) { e = partials[i] + e; }                       // 14
+             );
+           })
+       | then(                                                                // 15
+           [ = ](std::vector<double>&& partials) {                            // 15
+             return output;                                                   // 15
+           });                                                                // 15
+}
+
+

This example builds an asynchronous computation of an inclusive scan:

+
    +
  1. +

    It scans a sequence of doubles (represented as the std::span<const double> input) and stores the result in another sequence of doubles +(represented as std::span<double> output).

    +
  2. +

    It takes a scheduler, which specifies what execution resource the scan should +be launched on.

    +
  3. +

    It also takes a tile_count parameter that controls the number of execution +agents that will be spawned.

    +
  4. +

    First we need to allocate temporary storage needed for the algorithm, which +we’ll do with a std::vector, partials. We need one double of temporary +storage for each execution agent we create.

    +
  5. +

    Next we’ll create our initial sender with § 4.19.2 execution::just and § 4.20.1 execution::transfer. These senders will send the temporary +storage, which we’ve moved into the sender. The sender has a completion +scheduler of sch, which means the next item in the chain will use sch.

    +
  6. +

    Senders and sender adaptors support composition via operator|, similar to +C++ ranges. We’ll use operator| to attach the next piece of work, which +will spawn tile_count execution agents using § 4.20.9 execution::bulk (see § 4.12 Most sender adaptors are pipeable for details).

    +
  7. +

    Each agent will call a std::invocable, passing it two arguments. The first +is the agent’s index (i) in the § 4.20.9 execution::bulk operation, +in this case a unique integer in [0, tile_count). The second argument is +what the input sender sent - the temporary storage.

    +
  8. +

    We start by computing the start and end of the range of input and output +elements that this agent is responsible for, based on our agent index.

    +
  9. +

    Then we do a sequential std::inclusive_scan over our elements. We store the +scan result for our last element, which is the sum of all of our elements, +in our temporary storage partials.

    +
  10. +

    After all computation in that initial § 4.20.9 execution::bulk pass + has completed, every one of the spawned execution agents will have written + the sum of its elements into its slot in partials.

    +
  11. +

    Now we need to scan all of the values in partials. We’ll do that with a + single execution agent which will execute after the § 4.20.9 execution::bulk completes. We create that execution agent + with § 4.20.2 execution::then.

    +
  12. +

    § 4.20.2 execution::then takes an input sender and an std::invocable and calls the std::invocable with the value sent by the + input sender. Inside our std::invocable, we call std::inclusive_scan on partials, which the input senders will send to us.

    +
  13. +

    Then we return partials, which the next phase will need.

    +
  14. +

    Finally we do another § 4.20.9 execution::bulk of the same shape as + before. In this § 4.20.9 execution::bulk, we will use the scanned + values in partials to integrate the sums from other tiles into our + elements, completing the inclusive scan.

    +
  15. +

    async_inclusive_scan returns a sender that sends the output std::span<double>. A consumer of the algorithm can chain additional work + that uses the scan result. At the point at which async_inclusive_scan returns, the computation may not have completed. In fact, it may not have + even started.

    +
+

1.3.3. Asynchronous dynamically-sized read

+
using namespace std::execution;
+
+sender_of<std::size_t> auto async_read(                                       // 1
+    sender_of<std::span<std::byte>> auto buffer,                              // 1
+    auto handle);                                                             // 1
+
+struct dynamic_buffer {                                                       // 3
+  std::unique_ptr<std::byte[]> data;                                          // 3
+  std::size_t size;                                                           // 3
+};                                                                            // 3
+
+sender_of<dynamic_buffer> auto async_read_array(auto handle) {                // 2
+  return just(dynamic_buffer{})                                               // 4
+       | let_value([handle] (dynamic_buffer& buf) {                           // 5
+           return just(std::as_writeable_bytes(std::span(&buf.size, 1))       // 6
+                | async_read(handle)                                          // 7
+                | then(                                                       // 8
+                    [&buf] (std::size_t bytes_read) {                         // 9
+                      assert(bytes_read == sizeof(buf.size));                 // 10
+                      buf.data = std::make_unique<std::byte[]>(buf.size);     // 11
+                      return std::span(buf.data.get(), buf.size);             // 12
+                    })
+                | async_read(handle)                                          // 13
+                | then(
+                    [&buf] (std::size_t bytes_read) {
+                      assert(bytes_read == buf.size);                         // 14
+                      return std::move(buf);                                  // 15
+                    });
+       });
+}
+
+

This example demonstrates a common asynchronous I/O pattern - reading a payload +of a dynamic size by first reading the size, then reading the number of bytes +specified by the size:

+
    +
  1. +

    async_read is a pipeable sender adaptor. It’s a customization point object, +but this is what it’s call signature looks like. It takes a sender parameter +which must send an input buffer in the form of a std::span<std::byte>, and +a handle to an I/O context. It will asynchronously read into the input +buffer, up to the size of the std::span. It returns a sender which will +send the number of bytes read once the read completes.

    +
  2. +

    async_read_array takes an I/O handle and reads a size from it, and then a +buffer of that many bytes. It returns a sender that sends a dynamic_buffer object that owns the data that was sent.

    +
  3. +

    dynamic_buffer is an aggregate struct that contains a std::unique_ptr<std::byte[]> and a size.

    +
  4. +

    The first thing we do inside of async_read_array is create a sender that +will send a new, empty dynamic_array object using § 4.19.2 execution::just. We can attach more work to the pipeline +using operator| composition (see § 4.12 Most sender adaptors are pipeable for details).

    +
  5. +

    We need the lifetime of this dynamic_array object to last for the entire +pipeline. So, we use let_value, which takes an input sender and a std::invocable that must return a sender itself (see § 4.20.4 execution::let_* for details). let_value sends the value +from the input sender to the std::invocable. Critically, the lifetime of +the sent object will last until the sender returned by the std::invocable completes.

    +
  6. +

    Inside of the let_value std::invocable, we have the rest of our logic. +First, we want to initiate an async_read of the buffer size. To do that, +we need to send a std::span pointing to buf.size. We can do that with § 4.19.2 execution::just.

    +
  7. +

    We chain the async_read onto the § 4.19.2 execution::just sender +with operator|.

    +
  8. +

    Next, we pipe a std::invocable that will be invoked after the async_read completes using § 4.20.2 execution::then.

    +
  9. +

    That std::invocable gets sent the number of bytes read.

    +
  10. +

    We need to check that the number of bytes read is what we expected.

    +
  11. +

    Now that we have read the size of the data, we can allocate storage for it.

    +
  12. +

    We return a std::span<std::byte> to the storage for the data from the std::invocable. This will be sent to the next recipient in the pipeline.

    +
  13. +

    And that recipient will be another async_read, which will read the data.

    +
  14. +

    Once the data has been read, in another § 4.20.2 execution::then, we + confirm that we read the right number of bytes.

    +
  15. +

    Finally, we move out of and return our dynamic_buffer object. It will get + sent by the sender returned by async_read_array. We can attach more + things to that sender to use the data in the buffer.

    +
+

1.4. Asynchronous Windows socket recv

+

To get a better feel for how this interface might be used by low-level +operations see this example implementation of a cancellable async_recv() operation for a Windows Socket.

+
struct operation_base : WSAOVERALAPPED {
+    using completion_fn = void(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept;
+
+    // Assume IOCP event loop will call this when this OVERLAPPED structure is dequeued.
+    completion_fn* completed;
+};
+
+template<class Receiver>
+struct recv_op : operation_base {
+    using operation_state_concept = std::execution::operation_state_t;
+
+    recv_op(SOCKET s, void* data, size_t len, Receiver r)
+    : receiver(std::move(r))
+    , sock(s) {
+        this->Internal = 0;
+        this->InternalHigh = 0;
+        this->Offset = 0;
+        this->OffsetHigh = 0;
+        this->hEvent = NULL;
+        this->completed = &recv_op::on_complete;
+        buffer.len = len;
+        buffer.buf = static_cast<CHAR*>(data);
+    }
+
+    void start() & noexcept {
+        // Avoid even calling WSARecv() if operation already cancelled
+        auto st = std::execution::get_stop_token(
+          std::execution::get_env(receiver));
+        if (st.stop_requested()) {
+            std::execution::set_stopped(std::move(receiver));
+            return;
+        }
+
+        // Store and cache result here in case it changes during execution
+        const bool stopPossible = st.stop_possible();
+        if (!stopPossible) {
+            ready.store(true, std::memory_order_relaxed);
+        }
+
+        // Launch the operation
+        DWORD bytesTransferred = 0;
+        DWORD flags = 0;
+        int result = WSARecv(sock, &buffer, 1, &bytesTransferred, &flags,
+                             static_cast<WSAOVERLAPPED*>(this), NULL);
+        if (result == SOCKET_ERROR) {
+            int errorCode = WSAGetLastError();
+            if (errorCode != WSA_IO_PENDING) {
+                if (errorCode == WSA_OPERATION_ABORTED) {
+                    std::execution::set_stopped(std::move(receiver));
+                } else {
+                    std::execution::set_error(std::move(receiver),
+                                              std::error_code(errorCode, std::system_category()));
+                }
+                return;
+            }
+        } else {
+            // Completed synchronously (assuming FILE_SKIP_COMPLETION_PORT_ON_SUCCESS has been set)
+            execution::set_value(std::move(receiver), bytesTransferred);
+            return;
+        }
+
+        // If we get here then operation has launched successfully and will complete asynchronously.
+        // May be completing concurrently on another thread already.
+        if (stopPossible) {
+            // Register the stop callback
+            stopCallback.emplace(std::move(st), cancel_cb{*this});
+
+            // Mark as 'completed'
+            if (ready.load(std::memory_order_acquire) ||
+                ready.exchange(true, std::memory_order_acq_rel)) {
+                // Already completed on another thread
+                stopCallback.reset();
+
+                BOOL ok = WSAGetOverlappedResult(sock, (WSAOVERLAPPED*)this, &bytesTransferred, FALSE, &flags);
+                if (ok) {
+                    std::execution::set_value(std::move(receiver), bytesTransferred);
+                } else {
+                    int errorCode = WSAGetLastError();
+                    std::execution::set_error(std::move(receiver),
+                                              std::error_code(errorCode, std::system_category()));
+                }
+            }
+        }
+    }
+
+    struct cancel_cb {
+        recv_op& op;
+
+        void operator()() noexcept {
+            CancelIoEx((HANDLE)op.sock, (OVERLAPPED*)(WSAOVERLAPPED*)&op);
+        }
+    };
+
+    static void on_complete(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept {
+        recv_op& self = *static_cast<recv_op*>(op);
+
+        if (self.ready.load(std::memory_order_acquire) ||
+            self.ready.exchange(true, std::memory_order_acq_rel)) {
+            // Unsubscribe any stop-callback so we know that CancelIoEx() is not accessing 'op'
+            // any more
+            self.stopCallback.reset();
+
+            if (errorCode == 0) {
+                std::execution::set_value(std::move(self.receiver), bytesTransferred);
+            } else {
+                std::execution::set_error(std::move(self.receiver),
+                                          std::error_code(errorCode, std::system_category()));
+            }
+        }
+    }
+
+    using stop_callback_t = stop_callback_of_t<stop_token_of_t<env_of_t<Receiver>>, cancel_cb>;
+
+    Receiver receiver;
+    SOCKET sock;
+    WSABUF buffer;
+    std::optional<stop_callback_t> stopCallback;
+    std::atomic<bool> ready{false};
+};
+
+struct recv_sender {
+    using sender_concept = std::execution::sender_t;
+    SOCKET sock;
+    void* data;
+    size_t len;
+
+    template<class Receiver>
+    recv_op<Receiver> connect(Receiver r) const {
+        return recv_op<Receiver>{sock, data, len, std::move(r)};
+    }
+};
+
+recv_sender async_recv(SOCKET s, void* data, size_t len) {
+    return recv_sender{s, data, len};
+}
+
+

1.4.1. More end-user examples

+
1.4.1.1. Sudoku solver
+

This example comes from Kirk Shoop, who ported an example from TBB’s +documentation to sender/receiver in his fork of the libunifex repo. It is a +Sudoku solver that uses a configurable number of threads to explore the search +space for solutions.

+

The sender/receiver-based Sudoku solver can be found here. +Some things that are worth noting about Kirk’s solution:

+
    +
  1. +

    Although it schedules asychronous work onto a thread pool, and each unit of +work will schedule more work, its use of structured concurrency patterns +make reference counting unnecessary. The solution does not make use of shared_ptr.

    +
  2. +

    In addition to eliminating the need for reference counting, the use of +structured concurrency makes it easy to ensure that resources are cleaned up +on all code paths. In contrast, the TBB example that inspired this one leaks memory.

    +
+

For comparison, the TBB-based Sudoku solver can be found here.

+
1.4.1.2. File copy
+

This example also comes from Kirk Shoop which uses sender/receiver to +recursively copy the files a directory tree. It demonstrates how sender/receiver +can be used to do IO, using a scheduler that schedules work on Linux’s io_uring.

+

As with the Sudoku example, this example obviates the need for reference +counting by employing structured concurrency. It uses iteration with an upper +limit to avoid having too many open file handles.

+

You can find the example here.

+
1.4.1.3. Echo server
+

Dietmar Kuehl has proposed networking APIs that use the sender/receiver +abstraction (see P2762). He has implemented an echo +server as a demo. His echo server code can be found here.

+

Below, I show the part of the echo server code. This code is executed for each +client that connects to the echo server. In a loop, it reads input from a socket +and echos the input back to the same socket. All of this, including the loop, is +implemented with generic async algorithms.

+
outstanding.start(
+    EX::repeat_effect_until(
+          EX::let_value(
+              NN::async_read_some(ptr->d_socket,
+                                  context.scheduler(),
+                                  NN::buffer(ptr->d_buffer))
+        | EX::then([ptr](::std::size_t n){
+            ::std::cout << "read='" << ::std::string_view(ptr->d_buffer, n) << "'\n";
+            ptr->d_done = n == 0;
+            return n;
+        }),
+          [&context, ptr](::std::size_t n){
+            return NN::async_write_some(ptr->d_socket,
+                                        context.scheduler(),
+                                        NN::buffer(ptr->d_buffer, n));
+          })
+        | EX::then([](auto&&...){})
+        , [owner = ::std::move(owner)]{ return owner->d_done; }
+    )
+);
+
+

In this code, NN::async_read_some and NN::async_write_some are asynchronous +socket-based networking APIs that return senders. EX::repeat_effect_until, EX::let_value, and EX::then are fully generic sender adaptor algorithms that +accept and return senders.

+

This is a good example of seamless composition of async IO functions with non-IO +operations. And by composing the senders in this structured way, all the state +for the composite operation -- the repeat_effect_until expression and all its +child operations -- is stored altogether in a single object.

+

1.5. Examples: Algorithms

+

In this section we show a few simple sender/receiver-based algorithm +implementations.

+

1.5.1. then

+
namespace stdexec = std::execution;
+
+template <class R, class F>
+class _then_receiver : public R {
+  F f_;
+
+ public:
+  _then_receiver(R r, F f) : R(std::move(r)), f_(std::move(f)) {}
+
+  // Customize set_value by invoking the callable and passing the result to
+  // the inner receiver
+  template <class... As>
+    requires std::invocable<F, As...>
+  void set_value(As&&... as) && noexcept {
+    try {
+      stdexec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...));
+    } catch(...) {
+      stdexec::set_error(std::move(*this).base(), std::current_exception());
+    }
+  }
+};
+
+template <stdexec::sender S, class F>
+struct _then_sender {
+  using sender_concept = stdexec::sender_t;
+  S s_;
+  F f_;
+
+  template <class... Args>
+    using _set_value_t = stdexec::completion_signatures<
+      stdexec::set_value_t(std::invoke_result_t<F, Args...>)>;
+
+  using _except_ptr_sig =
+    stdexec::completion_signatures<stdexec::set_error_t(std::exception_ptr)>;
+
+  // Compute the completion signatures
+  template <class Env>
+  auto get_completion_signatures(Env&& env) && noexcept
+    -> stdexec::transform_completion_signatures_of<
+        S, Env, _except_ptr_sig, _set_value_t> {
+    return {};
+  }
+
+  // Connect:
+  template <stdexec::receiver R>
+  auto connect(R r) && -> stdexec::connect_result_t<S, _then_receiver<R, F>> {
+    return stdexec::connect(
+      (S&&) s_, _then_receiver{(R&&) r, (F&&) f_});
+  }
+
+  decltype(auto) get_env() const noexcept {
+    return get_env(s_);
+  }
+};
+
+template <stdexec::sender S, class F>
+stdexec::sender auto then(S s, F f) {
+  return _then_sender<S, F>{(S&&) s, (F&&) f};
+}
+
+

This code builds a then algorithm that transforms the value(s) from the input +sender with a transformation function. The result of the transformation becomes +the new value. The other receiver functions (set_error and set_stopped), as +well as all receiver queries, are passed through unchanged.

+

In detail, it does the following:

+
    +
  1. +

    Defines a receiver in terms of receiver and an invocable that:

    +
      +
    • +

      Defines a constrained set_value member function for transforming the +value channel.

      +
    • +

      Delegates set_error and set_stopped to the inner receiver.

      +
    +
  2. +

    Defines a sender that aggregates another sender and the invocable, which +defines a connect member function that wraps the incoming receiver in the +receiver from (1) and passes it and the incoming sender to std::execution::connect, returning the result. It also defines a get_completion_signatures member function that declares the sender’s +completion signatures when executed within a particular environment.

    +
+

1.5.2. retry

+
using namespace std;
+namespace stdexec = execution;
+
+template<class From, class To>
+concept _decays_to = same_as<decay_t<From>, To>;
+
+// _conv needed so we can emplace construct non-movable types into
+// a std::optional.
+template<invocable F>
+struct _conv {
+  F f_;
+
+  static_assert(is_nothrow_move_constructible_v<F>);
+  explicit _conv(F f) noexcept : f_((F&&) f) {}
+
+  operator invoke_result_t<F>() && {
+    return ((F&&) f_)();
+  }
+};
+
+template<class S, class R>
+struct _retry_op;
+
+// pass through all customizations except set_error, which retries
+// the operation.
+template<class S, class R>
+struct _retry_receiver {
+  _retry_op<S, R>* o_;
+
+  void set_value(auto&&... as) && noexcept {
+    stdexec::set_value(std::move(o_->r_), (decltype(as)&&) as...);
+  }
+
+  void set_error(auto&&) && noexcept {
+    o_->_retry(); // This causes the op to be retried
+  }
+
+  void set_stopped() && noexcept {
+    stdexec::set_stopped(std::move(o_->r_));
+  }
+
+  decltype(auto) get_env() const noexcept {
+    return get_env(o_->r_);
+  }
+};
+
+// Hold the nested operation state in an optional so we can
+// re-construct and re-start it if the operation fails.
+template<class S, class R>
+struct _retry_op {
+  using operation_state_concept = stdexec::operation_state_t;
+  using _child_op_t =
+    stdexec::connect_result_t<S&, _retry_receiver<S, R>>;
+
+  S s_;
+  R r_;
+  optional<_child_op_t> o_;
+
+  _op(_op&&) = delete;
+  _op(S s, R r)
+    : s_(std::move(s)), r_(std::move(r)), o_{_connect()} {}
+
+  auto _connect() noexcept {
+    return _conv{[this] {
+      return stdexec::connect(s_, _retry_receiver<S, R>{this});
+    }};
+  }
+
+  void _retry() noexcept {
+    try {
+      o_.emplace(_connect()); // potentially-throwing
+      stdexec::start(*o_);
+    } catch(...) {
+      stdexec::set_error(std::move(r_), std::current_exception());
+    }
+  }
+
+  void start() & noexcept {
+    stdexec::start(*o_);
+  }
+};
+
+// Helpers for computing the <code data-opaque bs-autolink-syntax='`then`'>then</code> sender’s completion signatures: 
+template <class... Ts>
+  using _value_t =
+    stdexec::completion_signatures<stdexec::set_value_t(Ts...)>;
+
+template <class>
+  using _error_t = stdexec::completion_signatures<>;
+
+using _except_sig =
+  stdexec::completion_signatures<stdexec::set_error_t(std::exception_ptr)>;
+
+template<class S>
+struct _retry_sender {
+  using sender_concept = stdexec::sender_t;
+  S s_;
+  explicit _retry_sender(S s) : s_(std::move(s)) {}
+
+  // Declare the signatures with which this sender can complete
+  template <class Env>
+    using _compl_sigs =
+      stdexec::transform_completion_signatures_of<
+        S&, Env, _except_sig, _value_t, _error_t>;
+
+  template <class Env>
+  auto get_completion_signatures(Env&&) const noexcept -> _compl_sigs<Env> {
+    return {};
+  }
+
+  template <stdexec::receiver R>
+    requires stdexec::sender_to<S&, _retry_receiver<S, R>>
+  _retry_op<S, R> connect(R r) && {
+    return {std::move(s_), std::move(r)};
+  }
+
+  decltype(auto) get_env() const noexcept {
+    return get_env(s_);
+  }
+};
+
+template <stdexec::sender S>
+stdexec::sender auto retry(S s) {
+  return _retry_sender{std::move(s)};
+}
+
+

The retry algorithm takes a multi-shot sender and causes it to repeat on +error, passing through values and stopped signals. Each time the input sender is +restarted, a new receiver is connected and the resulting operation state is +stored in an optional, which allows us to reinitialize it multiple times.

+

This example does the following:

+
    +
  1. +

    Defines a _conv utility that takes advantage of C++17’s guaranteed copy +elision to emplace a non-movable type in a std::optional.

    +
  2. +

    Defines a _retry_receiver that holds a pointer back to the operation state. +It passes all customizations through unmodified to the inner receiver owned +by the operation state except for set_error, which causes a _retry() function to be called instead.

    +
  3. +

    Defines an operation state that aggregates the input sender and receiver, and +declares storage for the nested operation state in an optional. +Constructing the operation state constructs a _retry_receiver with a +pointer to the (under construction) operation state and uses it to connect +to the input sender.

    +
  4. +

    Starting the operation state dispatches to start on the inner operation +state.

    +
  5. +

    The _retry() function reinitializes the inner operation state by connecting +the sender to a new receiver, holding a pointer back to the outer operation +state as before.

    +
  6. +

    After reinitializing the inner operation state, _retry() calls start on +it, causing the failed operation to be rescheduled.

    +
  7. +

    Defines a _retry_sender that implements a connect member function to +return an operation state constructed from the passed-in sender and +receiver.

    +
  8. +

    _retry_sender also implements a get_completion_signatures member function +to describe the ways this sender may complete when executed in a particular +execution resource.

    +
+

1.6. Examples: Schedulers

+

In this section we look at some schedulers of varying complexity.

+

1.6.1. Inline scheduler

+
namespace stdexec = std::execution;
+
+class inline_scheduler {
+  template <class R>
+  struct _op {
+    using operation_state_concept = operation_state_t;
+    R rec_;
+
+    void start() & noexcept {
+      stdexec::set_value(std::move(rec_));
+    }
+  };
+
+  struct _env {
+    template <class Tag>
+    inline_scheduler query(stdexec::get_completion_scheduler_t<Tag>) const noexcept {
+      return {};
+    }
+  };
+
+  struct _sender {
+    using sender_concept = stdexec::sender_t;
+    using _compl_sigs = stdexec::completion_signatures<stdexec::set_value_t()>;
+    using completion_signatures = _compl_sigs;
+
+    template <stdexec::receiver_of<_compl_sigs> R>
+    _op<R> connect(R rec) noexcept(std::is_nothrow_move_constructible_v<R>) {
+      return {std::move(rec)};
+    }
+
+    _env get_env() const noexcept {
+      return {};
+    }
+  };
+
+ public:
+  inline_scheduler() = default;
+
+  _sender schedule() const noexcept {
+    return {};
+  }
+
+  bool operator==(const inline_scheduler&) const noexcept = default;
+};
+
+

The inline scheduler is a trivial scheduler that completes immediately and +synchronously on the thread that calls std::execution::start on the operation +state produced by its sender. In other words, start(connect(schedule(inline_scheduler()), receiver)) is just a fancy way of +saying set_value(receiver), with the exception of the fact that start wants +to be passed an lvalue.

+

Although not a particularly useful scheduler, it serves to illustrate the basics +of implementing one. The inline_scheduler:

+
    +
  1. +

    Customizes execution::schedule to return an instance of the sender type _sender.

    +
  2. +

    The _sender type models the sender concept and provides the metadata +needed to describe it as a sender of no values +and that never calls set_error or set_stopped. This +metadata is provided with the help of the execution::completion_signatures utility.

    +
  3. +

    The _sender type customizes execution::connect to accept a receiver of no +values. It returns an instance of type _op that holds the receiver by +value.

    +
  4. +

    The operation state customizes std::execution::start to call std::execution::set_value on the receiver.

    +
+

1.6.2. Single thread scheduler

+

This example shows how to create a scheduler for an execution resource that +consists of a single thread. It is implemented in terms of a lower-level +execution resource called std::execution::run_loop.

+
class single_thread_context {
+  std::execution::run_loop loop_;
+  std::thread thread_;
+
+public:
+  single_thread_context()
+    : loop_()
+    , thread_([this] { loop_.run(); })
+  {}
+  single_thread_context(single_thread_context&&) = delete;
+
+  ~single_thread_context() {
+    loop_.finish();
+    thread_.join();
+  }
+
+  auto get_scheduler() noexcept {
+    return loop_.get_scheduler();
+  }
+
+  std::thread::id get_thread_id() const noexcept {
+    return thread_.get_id();
+  }
+};
+
+

The single_thread_context owns an event loop and a thread to drive it. In the +destructor, it tells the event loop to finish up what it’s doing and then joins +the thread, blocking for the event loop to drain.

+

The interesting bits are in the execution::run_loop context implementation. It +is slightly too long to include here, so we only provide a reference to +it, +but there is one noteworthy detail about its implementation: It uses space in +its operation states to build an intrusive linked list of work items. In +structured concurrency patterns, the operation states of nested operations +compose statically, and in an algorithm like this_thread::sync_wait, the +composite operation state lives on the stack for the duration of the operation. +The end result is that work can be scheduled onto this thread with zero +allocations.

+

1.7. Examples: Server theme

+

In this section we look at some examples of how one would use senders to +implement an HTTP server. The examples ignore the low-level details of the HTTP +server and looks at how senders can be combined to achieve the goals of the +project.

+

General application context:

+
    +
  • +

    server application that processes images

    +
  • +

    execution resources:

    +
      +
    • +

      1 dedicated thread for network I/O

      +
    • +

      N worker threads used for CPU-intensive work

      +
    • +

      M threads for auxiliary I/O

      +
    • +

      optional GPU context that may be used on some types of servers

      +
    +
  • +

    all parts of the applications can be asynchronous

    +
  • +

    no locks shall be used in user code

    +
+

1.7.1. Composability with execution::let_*

+

Example context:

+
    +
  • +

    we are looking at the flow of processing an HTTP request and sending back the +response.

    +
  • +

    show how one can break the (slightly complex) flow into steps with execution::let_* functions.

    +
  • +

    different phases of processing HTTP requests are broken down into separate +concerns.

    +
  • +

    each part of the processing might use different execution resources (details +not shown in this example).

    +
  • +

    error handling is generic, regardless which component fails; we always send +the right response to the clients.

    +
+

Goals:

+
    +
  • +

    show how one can break more complex flows into steps with let_* functions.

    +
  • +

    exemplify the use of let_value, let_error, let_stopped, and just algorithms.

    +
+
namespace stdexec = std::execution;
+
+// Returns a sender that yields an http_request object for an incoming request
+stdexec::sender auto schedule_request_start(read_requests_ctx ctx) {...}
+
+// Sends a response back to the client; yields a void signal on success
+stdexec::sender auto send_response(const http_response& resp) {...}
+
+// Validate that the HTTP request is well-formed; forwards the request on success
+stdexec::sender auto validate_request(const http_request& req) {...}
+
+// Handle the request; main application logic
+stdexec::sender auto handle_request(const http_request& req) {
+  //...
+  return stdexec::just(http_response{200, result_body});
+}
+
+// Transforms server errors into responses to be sent to the client
+stdexec::sender auto error_to_response(std::exception_ptr err) {
+  try {
+    std::rethrow_exception(err);
+  } catch (const std::invalid_argument& e) {
+    return stdexec::just(http_response{404, e.what()});
+  } catch (const std::exception& e) {
+    return stdexec::just(http_response{500, e.what()});
+  } catch (...) {
+    return stdexec::just(http_response{500, "Unknown server error"});
+  }
+}
+
+// Transforms cancellation of the server into responses to be sent to the client
+stdexec::sender auto stopped_to_response() {
+  return stdexec::just(http_response{503, "Service temporarily unavailable"});
+}
+
+//...
+
+// The whole flow for transforming incoming requests into responses
+stdexec::sender auto snd =
+    // get a sender when a new request comes
+    schedule_request_start(the_read_requests_ctx)
+    // make sure the request is valid; throw if not
+    | stdexec::let_value(validate_request)
+    // process the request in a function that may be using a different execution resource
+    | stdexec::let_value(handle_request)
+    // If there are errors transform them into proper responses
+    | stdexec::let_error(error_to_response)
+    // If the flow is cancelled, send back a proper response
+    | stdexec::let_stopped(stopped_to_response)
+    // write the result back to the client
+    | stdexec::let_value(send_response)
+    // done
+    ;
+
+// execute the whole flow asynchronously
+stdexec::start_detached(std::move(snd));
+
+

The example shows how one can separate out the concerns for interpreting +requests, validating requests, running the main logic for handling the request, +generating error responses, handling cancellation and sending the response back +to the client. They are all different phases in the application, and can be +joined together with the let_* functions.

+

All our functions return execution::sender objects, so that they can all +generate success, failure and cancellation paths. For example, regardless where +an error is generated (reading request, validating request or handling the +response), we would have one common block to handle the error, and following +error flows is easy.

+

Also, because of using execution::sender objects at any step, we might expect +any of these steps to be completely asynchronous; the overall flow doesn’t care. +Regardless of the execution resource in which the steps, or part of the steps +are executed in, the flow is still the same.

+

1.7.2. Moving between execution resources with execution::on and execution::transfer

+

Example context:

+
    +
  • +

    reading data from the socket before processing the request

    +
  • +

    reading of the data is done on the I/O context

    +
  • +

    no processing of the data needs to be done on the I/O context

    +
+

Goals:

+
    +
  • +

    show how one can change the execution resource

    +
  • +

    exemplify the use of on and transfer algorithms

    +
+
namespace stdexec = std::execution;
+
+size_t legacy_read_from_socket(int sock, char* buffer, size_t buffer_len);
+void process_read_data(const char* read_data, size_t read_len);
+//...
+
+// A sender that just calls the legacy read function
+auto snd_read = stdexec::just(sock, buf, buf_len)
+              | stdexec::then(legacy_read_from_socket);
+
+// The entire flow
+auto snd =
+    // start by reading data on the I/O thread
+    stdexec::on(io_sched, std::move(snd_read))
+    // do the processing on the worker threads pool
+    | stdexec::transfer(work_sched)
+    // process the incoming data (on worker threads)
+    | stdexec::then([buf](int read_len) { process_read_data(buf, read_len); })
+    // done
+    ;
+
+// execute the whole flow asynchronously
+stdexec::start_detached(std::move(snd));
+
+

The example assume that we need to wrap some legacy code of reading sockets, and +handle execution resource switching. (This style of reading from socket may not +be the most efficient one, but it’s working for our purposes.) For performance +reasons, the reading from the socket needs to be done on the I/O thread, and all +the processing needs to happen on a work-specific execution resource (i.e., +thread pool).

+

Calling execution::on will ensure that the given sender will be started on the +given scheduler. In our example, snd_read is going to be started on the I/O +scheduler. This sender will just call the legacy code.

+

The completion-signal will be issued in the I/O execution resource, so we have +to move it to the work thread pool. This is achieved with the help of the execution::transfer algorithm. The rest of the processing (in our case, the +last call to then) will happen in the work thread pool.

+

The reader should notice the difference between execution::on and execution::transfer. The execution::on algorithm will ensure that the given +sender will start in the specified context, and doesn’t care where the +completion-signal for that sender is sent. The execution::transfer algorithm +will not care where the given sender is going to be started, but will ensure +that the completion-signal of will be transferred to the given context.

+

1.8. Design changes from P0443

+
    +
  1. +

    The executor concept has been removed and all of its proposed functionality +is now based on schedulers and senders, as per SG1 direction.

    +
  2. +

    Properties are not included in this paper. We see them as a possible future +extension, if the committee gets more comfortable with them.

    +
  3. +

    Senders now advertise what scheduler, if any, their evaluation will complete +on.

    +
  4. +

    The places of execution of user code in P0443 weren’t precisely defined, +whereas they are in this paper. See § 4.5 Senders can propagate completion schedulers.

    +
  5. +

    P0443 did not propose a suite of sender algorithms necessary for writing +sender code; this paper does. See § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers.

    +
  6. +

    P0443 did not specify the semantics of variously qualified connect overloads; this paper does. See § 4.7 Senders can be either multi-shot or single-shot.

    +
  7. +

    This paper extends the sender traits/typed sender design to support typed +senders whose value/error types depend on type information provided late via +the receiver.

    +
  8. +

    Support for untyped senders is dropped; the typed_sender concept is renamed sender; sender_traits is replaced with completion_signatures_of_t.

    +
  9. +

    Specific type erasure facilities are omitted, as per LEWG direction. Type +erasure facilities can be built on top of this proposal, as discussed in § 5.9 Customization points.

    +
  10. +

    A specific thread pool implementation is omitted, as per LEWG direction.

    +
  11. +

    Some additional utilities are added:

    +
      +
    • +

      run_loop: An execution resource that provides a multi-producer, +single-consumer, first-in-first-out work queue.

      +
    • +

      completion_signatures and transform_completion_signatures: +Utilities for describing the ways in which a sender can complete in a +declarative syntax.

      +
    +
+

1.9. Prior art

+

This proposal builds upon and learns from years of prior art with asynchronous +and parallel programming frameworks in C++. In this section, we discuss async +abstractions that have previously been suggested as a possible basis for +asynchronous algorithms and why they fall short.

+

1.9.1. Futures

+

A future is a handle to work that has already been scheduled for execution. It +is one end of a communication channel; the other end is a promise, used to +receive the result from the concurrent operation and to communicate it to the +future.

+

Futures, as traditionally realized, require the dynamic allocation and +management of a shared state, synchronization, and typically type-erasure of +work and continuation. Many of these costs are inherent in the nature of +"future" as a handle to work that is already scheduled for execution. These +expenses rule out the future abstraction for many uses and makes it a poor +choice for a basis of a generic mechanism.

+

1.9.2. Coroutines

+

C++20 coroutines are frequently suggested as a basis for asynchronous +algorithms. It’s fair to ask why, if we added coroutines to C++, are we +suggesting the addition of a library-based abstraction for asynchrony. +Certainly, coroutines come with huge syntactic and semantic advantages over the +alternatives.

+

Although coroutines are lighter weight than futures, coroutines suffer many of +the same problems. Since they typically start suspended, they can avoid +synchronizing the chaining of dependent work. However in many cases, coroutine +frames require an unavoidable dynamic allocation and indirect function calls. +This is done to hide the layout of the coroutine frame from the C++ type system, +which in turn makes possible the separate compilation of coroutines and certain +compiler optimizations, such as optimization of the coroutine frame size.

+

Those advantages come at a cost, though. Because of the dynamic allocation of +coroutine frames, coroutines in embedded or heterogeneous environments, which +often lack support for dynamic allocation, require great attention to detail. +And the allocations and indirections tend to complicate the job of the inliner, +often resulting in sub-optimal codegen.

+

The coroutine language feature mitigates these shortcomings somewhat with the +HALO optimization Halo: coroutine Heap Allocation eLision Optimization: the joint response, which leverages existing compiler optimizations +such as allocation elision and devirtualization to inline the coroutine, +completely eliminating the runtime overhead. However, HALO requires a +sophisiticated compiler, and a fair number of stars need to align for the +optimization to kick in. In our experience, more often than not in real-world +code today’s compilers are not able to inline the coroutine, resulting in +allocations and indirections in the generated code.

+

In a suite of generic async algorithms that are expected to be callable from hot +code paths, the extra allocations and indirections are a deal-breaker. It is for +these reasons that we consider coroutines a poor choise for a basis of all +standard async.

+

1.9.3. Callbacks

+

Callbacks are the oldest, simplest, most powerful, and most efficient mechanism +for creating chains of work, but suffer problems of their own. Callbacks must +propagate either errors or values. This simple requirement yields many different +interface possibilities. The lack of a standard callback shape obstructs generic +design.

+

Additionally, few of these possibilities accommodate cancellation signals when +the user requests upstream work to stop and clean up.

+

1.10. Field experience

+

1.10.1. libunifex

+

This proposal draws heavily from our field experience with libunifex. Libunifex +implements all of the concepts and customization points defined in this paper +(with slight variations -- the design of P2300 has evolved due to LEWG +feedback), many of this paper’s algorithms (some under different names), and +much more besides.

+

Libunifex has several concrete schedulers in addition to the run_loop suggested here (where it is called manual_event_loop). It has schedulers that +dispatch efficiently to epoll and io_uring on Linux and the Windows Thread Pool +on Windows.

+

In addition to the proposed interfaces and the additional schedulers, it has +several important extensions to the facilities described in this paper, which +demonstrate directions in which these abstractions may be evolved over time, +including:

+
    +
  • +

    Timed schedulers, which permit scheduling work on an execution resource at a +particular time or after a particular duration has elapsed. In addition, it +provides time-based algorithms.

    +
  • +

    File I/O schedulers, which permit filesystem I/O to be scheduled.

    +
  • +

    Two complementary abstractions for streams (asynchronous ranges), and a set of +stream-based algorithms.

    +
+

Libunifex has seen heavy production use at Meta. An employee summarizes it +as follows:

+
+

As of June, 2023, Unifex is still used in production at Meta. It’s used to +express the asynchrony in rsys, and is +therefore serving video calling to billions of people every month on Meta’s +social networking apps on iOS, Android, Windows, and macOS. It’s also serving +the Virtual Desktop experience on Oculus Quest devices, and some internal uses +that run on Linux.

+

One team at Meta has migrated from folly::Future to unifex::task and seen +significant developer efficiency improvements. Coroutines are easier to +understand than chained futures so the team was able to meet requirements for +certain constrained environments that would have been too complicated to +maintain with futures.

+

In all the cases mentioned above, developers mix-and-match between the sender +algorithms in Unifex and Unifex’s coroutine type, unifex::task. We also rely +on unifex::task's scheduler affinity to minimize surprise when programming +with coroutines.

+
+

1.10.2. stdexec

+

stdexec is the reference implementation of +this proposal. It is a complete implementation, written from the specification +in this paper, and is current with \R8.

+

The original purpose of stdexec was to help find specification bugs and to +harden the wording of the proposal, but it has since become one of NVIDIA’s core +C++ libraries for high-performance computing. In addition to the facilities +proposed in this paper, stdexec has schedulers for CUDA, Intel TBB, and MacOS. +Like libunifex, its scope has also expanded to include a streaming abstraction +and stream algorithms, and time-based schedulers and algorithms.

+

The stdexec project has seen lots of community interest and contributions. At the +time of writing (March, 2024), the GitHub repository has 1.2k stars, 130 forks, +and 50 contributors.

+

stdexec is fit for broad use and for ultimate contribution to libc++.

+

1.10.3. Other implementations

+

The authors are aware of a number of other implementations of sender/receiver +from this paper. These are presented here in perceived order of maturity and +field experience.

+
    +
  • +

    HPX - The C++ Standard Library for Parallelism and Concurrency

    +

    HPX is a general purpose C++ runtime system for parallel and distributed +applications that has been under active development since 2007. HPX exposes +a uniform, standards-oriented API, and keeps abreast of the latest standards +and proposals. It is used in a wide variety of high-performance +applications.

    +

    The sender/receiver implementation in HPX has been under active development +since May 2020. It is used to erase the overhead of futures and to make it +possible to write efficient generic asynchronous algorithms that are +agnostic to their execution resource. In HPX, algorithms can migrate +execution between execution resources, even to GPUs and back, using a +uniform standard interface with sender/receiver.

    +

    Far and away, the HPX team has the greatest usage experience outside +Facebook. Mikael Simberg summarizes the experience as follows:

    +
    +

    Summarizing, for us the major benefits of sender/receiver compared to the +old model are:

    +
      +
    1. +

      Proper hooks for transitioning between execution resources.

      +
    2. +

      The adaptors. Things like let_value are really nice additions.

      +
    3. +

      Separation of the error channel from the value channel (also +cancellation, but we don’t have much use for it at the moment). Even +from a teaching perspective having to explain that the future f2 in +the continuation will always be ready here f1.then([](future<T> f2) {...}) is enough of a reason to separate the channels. All the other +obvious reasons apply as well of course.

      +
    4. +

      For futures we have a thing called hpx::dataflow which is an +optimized version of when_all(...).then(...) which avoids +intermediate allocations. With the sender/receiver when_all(...) | then(...) we get that "for free".

      +
    +
    +
  • +

    kuhllib by Dietmar Kuehl

    +

    This is a prototype Standard Template Library with an implementation of +sender/receiver that has been under development since May, 2021. It is +significant mostly for its support for sender/receiver-based networking +interfaces.

    +

    Here, Dietmar Kuehl speaks about the perceived complexity of +sender/receiver:

    +
    +

    ... and, also similar to STL: as I had tried to do things in that space +before I recognize sender/receivers as being maybe complicated in one way +but a huge simplification in another one: like with STL I think those who +use it will benefit - if not from the algorithm from the clarity of +abstraction: the separation of concerns of STL (the algorithm being +detached from the details of the sequence representation) is a major leap. +Here it is rather similar: the separation of the asynchronous algorithm +from the details of execution. Sure, there is some glue to tie things back +together but each of them is simpler than the combined result.

    +
    +

    Elsewhere, he said:

    +
    +

    ... to me it feels like sender/receivers are like iterators when STL +emerged: they are different from what everybody did in that space. +However, everything people are already doing in that space isn’t right.

    +
    +

    Kuehl also has experience teaching sender/receiver at Bloomberg. About that +experience he says:

    +
    +

    When I asked [my students] specifically about how complex they consider +the sender/receiver stuff the feedback was quite unanimous that the +sender/receiver parts aren’t trivial but not what contributes to the +complexity.

    +
    +
  • +

    C++ Bare Metal Senders and Receivers from Intel

    +

    This is a prototype implementation of sender/receiver by Intel that has been +under development since August, 2023. It is significant mostly for its +support for bare metal (no operating system) and embedded systems, a domain +for which senders are particularly well-suited due to their very low dynamic +memory requirements.

    +
+

1.10.4. Inspirations

+

This proposal also draws heavily from our experience with Thrust and Agency. It is also inspired by the +needs of countless other C++ frameworks for asynchrony, parallelism, and +concurrency, including:

+ +

2. Revision history

+

2.1. R9

+

The changes since R8 are as follows:

+

Fixes:

+
    +
  • +

    The tag_invoke mechanism has been replaced with member functions + for customizations as per P2855.

    +
  • +

    Per guidance from LWG and LEWG, receiver_adaptor has been removed.

    +
  • +

    The receiver concept is tweaked to require that receiver types are not final. Without receiver_adaptor and tag_invoke, receiver adaptors + are easily written using implementation inheritance.

    +
  • +

    std::tag_t is made exposition-only.

    +
  • +

    The types in_place_stop_token, in_place_stop_source, and in_place_stop_callback are renamed to inplace_stop_token, inplace_stop_source, and inplace_stop_callback, respectively.

    +
+

Enhancements:

+
    +
  • +

    The specification of the sync_wait algorithm has been updated + for clarity.

    +
  • +

    The specification of all the stop token, source, and callback types have + been re-expressed in terms of shared concepts.

    +
  • +

    Declarations are shown in their proper namespaces.

    +
  • +

    Editorial changes have been made to clarify what text is added, + what is removed, and what is an editorial note.

    +
  • +

    The section numbers of the proposed wording now match the section + numbers in the working draft of the C++ standard.

    +
+

2.2. R8

+

The changes since R7 are as follows:

+

Fixes:

+
    +
  • +

    get_env(obj) is required to be nothrow.

    +
  • +

    get_env and the associated environment utilities are moved back into std::execution from std::.

    +
  • +

    make_completion_signatures is renamed transform_completion_signatures_of and is expressed in terms of the new transform_completion_signatures, +which takes an input set of completion signatures instead of a sender and an +environment.

    +
  • +

    Add a requirement on queryable objects that if tag_invoke(query, env, args...) is well-formed, then query(env, args...) is +expression-equivalent to it. This is necessary to properly specify how to +join two environments in the presence of queries that have defaults.

    +
  • +

    The sender_in<Sndr, Env> concept requires that E satisfies queryable.

    +
  • +

    Senders of more than one value are now co_await-able in coroutines, the +result of which is a std::tuple of the values (which is suitable as the +initializer of a structured binding).

    +
+

Enhancements:

+
    +
  • +

    The exposition-only class template basic-sender is greatly +enhanced, and the sender algorithms are respecified in term of it.

    +
  • +

    enable_sender and enable_receiver traits now have default +implementations that look for nested sender_concept and receiver_concept types, respectively.

    +
+

2.3. R7

+

The changes since R6 are as follows:

+

Fixes:

+
    +
  • +

    Make it valid to pass non-variadic templates to the exposition-only alias +template gather-signatures, fixing the definitions of value_types_of_t, error_types_of_t, and the exposition-only alias +template sync-wait-result-type.

    +
  • +

    Removed the query forwarding from receiver_adaptor that was +inadvertantly left over from a previous edit.

    +
  • +

    When adapting a sender to an awaitable with as_awaitable, the sender’s +value result datum is decayed before being stored in the exposition-only variant.

    +
  • +

    Correctly specify the completion signatures of the schedule_from algorithm.

    +
  • +

    The sender_of concept no longer distinguishes between a sender of a +type T and a sender of a type T&&.

    +
  • +

    The just and just_error sender factories now reject C-style arrays +instead of silently decaying them to pointers.

    +
+

Enhancements:

+
    +
  • +

    The sender and receiver concepts get explicit opt-in traits called enable_sender and enable_receiver, respectively. The traits have +default implementations that look for nested is_sender and is_receiver types, respectively.

    +
  • +

    get_attrs is removed and get_env is used in its place.

    +
  • +

    The exposition-only type empty-env is made normative +and is renamed empty_env.

    +
  • +

    get_env gets a fall-back implementation that simply returns empty_env{} if a tag_invoke overload is not found.

    +
  • +

    get_env is required to be insensitive to the cvref-qualification of its +argument.

    +
  • +

    get_env, empty_env, and env_of_t are moved into the std:: namespace.

    +
  • +

    Add a new subclause describing the async programming model of senders in +abstract terms. See § 34.3 Asynchronous operations [async.ops].

    +
+

2.4. R6

+

The changes since R5 are as follows:

+

Fixes:

+
    +
  • +

    Fix typo in the specification of in_place_stop_source about the relative +lifetimes of the tokens and the source that produced them.

    +
  • +

    get_completion_signatures tests for awaitability with a promise type +similar to the one used by connect for the sake of consistency.

    +
  • +

    A coroutine promise type is an environment provider (that is, it implements get_env()) rather than being directly queryable. The previous draft was +inconsistent about that.

    +
+

Enhancements:

+
    +
  • +

    Sender queries are moved into a separate queryable "attributes" object +that is accessed by passing the sender to get_attrs() (see below). The sender concept is reexpressed to require get_attrs() and separated +from a new sender_in<Snd, Env> concept for checking whether a type is +a sender within a particular execution environment.

    +
  • +

    The placeholder types no_env and dependent_completion_signatures<> are no longer needed and are dropped.

    +
  • +

    ensure_started and split are changed to persist the result of +calling get_attrs() on the input sender.

    +
  • +

    Reorder constraints of the scheduler and receiver concepts to avoid +constraint recursion when used in tandem with poorly-constrained, implicitly +convertible types.

    +
  • +

    Re-express the sender_of concept to be more ergonomic and general.

    +
  • +

    Make the specification of the alias templates value_types_of_t and error_types_of_t, and the variable template sends_done more concise by +expressing them in terms of a new exposition-only alias template gather-signatures.

    +
+

2.4.1. Environments and attributes

+

In earlier revisions, receivers, senders, and schedulers all were directly +queryable. In R4, receiver queries were moved into a separate "environment" +object, obtainable from a receiver with a get_env accessor. In R6, the +sender queries are given similar treatment, relocating to a "attributes" +object obtainable from a sender with a get_attrs accessor. This was done +to solve a number of design problems with the split and ensure_started algorithms; _e.g._, see NVIDIA/stdexec#466.

+

Schedulers, however, remain directly queryable. As lightweight handles +that are required to be movable and copyable, there is little reason to +want to dispose of a scheduler and yet persist the scheduler’s queries.

+

This revision also makes operation states directly queryable, even though +there isn’t yet a use for such. Some early prototypes of cooperative bulk +parallel sender algorithms done at NVIDIA suggest the utility of +forwardable operation state queries. The authors chose to make opstates +directly queryable since the opstate object is itself required to be kept +alive for the duration of asynchronous operation.

+

2.5. R5

+

The changes since R4 are as follows:

+

Fixes:

+
    +
  • +

    start_detached requires its argument to be a void sender (sends no values +to set_value).

    +
+

Enhancements:

+
    +
  • +

    Receiver concepts refactored to no longer require an error channel for exception_ptr or a stopped channel.

    +
  • +

    sender_of concept and connect customization point additionally require +that the receiver is capable of receiving all of the sender’s possible +completions.

    +
  • +

    get_completion_signatures is now required to return an instance of either completion_signatures or dependent_completion_signatures.

    +
  • +

    make_completion_signatures made more general.

    +
  • +

    receiver_adaptor handles get_env as it does the set_* members; that is, receiver_adaptor will look for a member named get_env() in the derived +class, and if found dispatch the get_env_t tag invoke customization to it.

    +
  • +

    just, just_error, just_stopped, and into_variant have been respecified +as customization point objects instead of functions, following LEWG guidance.

    +
+

2.6. R4

+

The changes since R3 are as follows:

+

Fixes:

+
    +
  • +

    Fix specification of get_completion_scheduler on the transfer, schedule_from and transfer_when_all algorithms; the completion scheduler cannot be guaranteed +for set_error.

    +
  • +

    The value of sends_stopped for the default sender traits of types that are +generally awaitable was changed from false to true to acknowledge the +fact that some coroutine types are generally awaitable and may implement the unhandled_stopped() protocol in their promise types.

    +
  • +

    Fix the incorrect use of inline namespaces in the <execution> header.

    +
  • +

    Shorten the stable names for the sections.

    +
  • +

    sync_wait now handles std::error_code specially by throwing a std::system_error on failure.

    +
  • +

    Fix how ADL isolation from class template arguments is specified so it +doesn’t constrain implmentations.

    +
  • +

    Properly expose the tag types in the header <execution> synopsis.

    +
+

Enhancements:

+
    +
  • +

    Support for "dependently-typed" senders, where the completion signatures -- and +thus the sender metadata -- depend on the type of the receiver connected +to it. See the section dependently-typed +senders below for more information.

    +
  • +

    Add a read(query) sender factory for issuing a query +against a receiver and sending the result through the value channel. (This is +a useful instance of a dependently-typed sender.)

    +
  • +

    Add completion_signatures utility for declaratively defining a typed +sender’s metadata.

    +
  • +

    Add make_completion_signatures utility for specifying a sender’s completion +signatures by adapting those of another sender.

    +
  • +

    Drop support for untyped senders and rename typed_sender to sender.

    +
  • +

    set_done is renamed to set_stopped. All occurances of "done" in +indentifiers replaced with "stopped"

    +
  • +

    Add customization points for controlling the forwarding of scheduler, +sender, receiver, and environment queries through layers of adaptors; +specify the behavior of the standard adaptors in terms of the new +customization points.

    +
  • +

    Add get_delegatee_scheduler query to forward a scheduler that can be used +by algorithms or by the scheduler to delegate work and forward progress.

    +
  • +

    Add schedule_result_t alias template.

    +
  • +

    More precisely specify the sender algorithms, including precisely what their +completion signatures are.

    +
  • +

    stopped_as_error respecified as a customization point object.

    +
  • +

    tag_invoke respecified to improve diagnostics.

    +
+

2.6.1. Dependently-typed senders

+

Background:

+

In the sender/receiver model, as with coroutines, contextual information about +the current execution is most naturally propagated from the consumer to the +producer. In coroutines, that means information like stop tokens, allocators and +schedulers are propagated from the calling coroutine to the callee. In +sender/receiver, that means that that contextual information is associated with +the receiver and is queried by the sender and/or operation state after the +sender and the receiver are connect-ed.

+

Problem:

+

The implication of the above is that the sender alone does not have all the +information about the async computation it will ultimately initiate; some of +that information is provided late via the receiver. However, the sender_traits mechanism, by which an algorithm can introspect the value and error types the +sender will propagate, only accepts a sender parameter. It does not take into +consideration the type information that will come in late via the receiver. The +effect of this is that some senders cannot be typed senders when they +otherwise could be.

+

Example:

+

To get concrete, consider the case of the "get_scheduler()" sender: when connect-ed and start-ed, it queries the receiver for its associated +scheduler and passes it back to the receiver through the value channel. That +sender’s "value type" is the type of the receiver’s scheduler. What then +should sender_traits<get_scheduler_sender>::value_types report for the get_scheduler()'s value type? It can’t answer because it doesn’t know.

+

This causes knock-on problems since some important algorithms require a typed +sender, such as sync_wait. To illustrate the problem, consider the following +code:

+
namespace ex = std::execution;
+
+ex::sender auto task =
+  ex::let_value(
+    ex::get_scheduler(), // Fetches scheduler from receiver.
+    [](auto current_sched) {
+      // Lauch some nested work on the current scheduler:
+      return ex::on(current_sched, nested work...);
+    });
+
+std::this_thread::sync_wait(std::move(task));
+
+

The code above is attempting to schedule some work onto the sync_wait's run_loop execution resource. But let_value only returns a typed sender when +the input sender is typed. As we explained above, get_scheduler() is not +typed, so task is likewise not typed. Since task isn’t typed, it cannot be +passed to sync_wait which is expecting a typed sender. The above code would +fail to compile.

+

Solution:

+

The solution is conceptually quite simple: extend the sender_traits mechanism +to optionally accept a receiver in addition to the sender. The algorithms can +use sender_traits<Sender, Receiver> to inspect the +async operation’s completion-signals. The typed_sender concept would also need +to take an optional receiver parameter. This is the simplest change, and it +would solve the immediate problem.

+

Design:

+

Using the receiver type to compute the sender traits turns out to have pitfalls +in practice. Many receivers make use of that type information in their +implementation. It is very easy to create cycles in the type system, leading to +inscrutible errors. The design pursued in R4 is to give receivers an associated environment object -- a bag of key/value pairs -- and to move the contextual +information (schedulers, etc) out of the receiver and into the environment. The sender_traits template and the typed_sender concept, rather than taking a +receiver, take an environment. This is a much more robust design.

+

A further refinement of this design would be to separate the receiver and the +environment entirely, passing then as separate arguments along with the sender to connect. This paper does not propose that change.

+

Impact:

+

This change, apart from increasing the expressive power of the sender/receiver +abstraction, has the following impact:

+
    +
  • +

    Typed senders become moderately more challenging to write. (The new completion_signatures and transform_completion_signatures utilities are +added to ease this extra burden.)

    +
  • +

    Sender adaptor algorithms that previously constrained their sender arguments +to satisfy the typed_sender concept can no longer do so as the receiver is +not available yet. This can result in type-checking that is done later, when connect is ultimately called on the resulting sender adaptor.

    +
  • +

    Operation states that own receivers that add to or change the environment +are typically larger by one pointer. It comes with the benefit of far fewer +indirections to evaluate queries.

    +
+

"Has it been implemented?"

+

Yes, the reference implementation, which can be found at https://github.com/NVIDIA/stdexec, has +implemented this design as well as some dependently-typed senders to confirm +that it works.

+

Implementation experience

+

Although this change has not yet been made in libunifex, the most widely adopted +sender/receiver implementation, a similar design can be found in Folly’s +coroutine support library. In Folly.Coro, it is possible to await a special +awaitable to obtain the current coroutine’s associated scheduler (called an +executor in Folly).

+

For instance, the following Folly code grabs the current executor, schedules a +task for execution on that executor, and starts the resulting (scheduled) task +by enqueueing it for execution.

+
// From Facebook’s Folly open source library:
+template <class T>
+folly::coro::Task<void> CancellableAsyncScope::co_schedule(folly::coro::Task<T>&& task) {
+  this->add(std::move(task).scheduleOn(co_await co_current_executor));
+  co_return;
+}
+
+

Facebook relies heavily on this pattern in its coroutine code. But as described +above, this pattern doesn’t work with R3 of std::execution because of the lack +of dependently-typed schedulers. The change to sender_traits in R4 rectifies that.

+

Why now?

+

The authors are loathe to make any changes to the design, however small, at this +stage of the C++23 release cycle. But we feel that, for a relatively minor +design change -- adding an extra template parameter to sender_traits and typed_sender -- the returns are large enough to justify the change. And there +is no better time to make this change than as early as possible.

+

One might wonder why this missing feature not been added to sender/receiver +before now. The designers of sender/receiver have long been aware of the need. +What was missing was a clean, robust, and simple design for the change, which we +now have.

+

Drive-by:

+

We took the opportunity to make an additional drive-by change: Rather than +providing the sender traits via a class template for users to specialize, we +changed it into a sender query: get_completion_signatures(sender, env). That function’s return type is used as the sender’s traits. +The authors feel this leads to a more uniform design and gives sender authors a +straightforward way to make the value/error types dependent on the cv- and +ref-qualification of the sender if need be.

+

Details:

+

Below are the salient parts of the new support for dependently-typed senders in +R4:

+
    +
  • +

    Receiver queries have been moved from the receiver into a separate environment +object.

    +
  • +

    Receivers have an associated environment. The new get_env CPO retrieves a +receiver’s environment. If a receiver doesn’t implement get_env, it +returns an unspecified "empty" environment -- an empty struct.

    +
  • +

    sender_traits now takes an optional Env parameter that is used to +determine the error/value types.

    +
  • +

    The primary sender_traits template is replaced with a completion_signatures_of_t alias implemented in terms of a new get_completion_signatures CPO that dispatches with tag_invoke. get_completion_signatures takes a sender and an optional environment. A +sender can customize this to specify its value/error types.

    +
  • +

    Support for untyped senders is dropped. The typed_sender concept has been +renamed to sender and now takes an optional environment.

    +
  • +

    The environment argument to the sender concept and the get_completion_signatures CPO defaults to no_env. All environment +queries fail (are ill-formed) when passed an instance of no_env.

    +
  • +

    A type S is required to satisfy sender<S> to be +considered a sender. If it doesn’t know what types it will complete with +independent of an environment, it returns an instance of the placeholder +traits dependent_completion_signatures.

    +
  • +

    If a sender satisfies both sender<S> and sender<S, Env>, then the completion signatures +for the two cannot be different in any way. It is possible for an +implementation to enforce this statically, but not required.

    +
  • +

    All of the algorithms and examples have been updated to work with +dependently-typed senders.

    +
+

2.7. R3

+

The changes since R2 are as follows:

+

Fixes:

+
    +
  • +

    Fix specification of the on algorithm to clarify lifetimes of intermediate +operation states and properly scope the get_scheduler query.

    +
  • +

    Fix a memory safety bug in the implementation of connect-awaitable.

    +
  • +

    Fix recursive definition of the scheduler concept.

    +
+

Enhancements:

+
    +
  • +

    Add run_loop execution resource.

    +
  • +

    Add receiver_adaptor utility to simplify writing receivers.

    +
  • +

    Require a scheduler’s sender to model sender_of and provide a completion +scheduler.

    +
  • +

    Specify the cancellation scope of the when_all algorithm.

    +
  • +

    Make as_awaitable a customization point.

    +
  • +

    Change connect's handling of awaitables to consider those types that are +awaitable owing to customization of as_awaitable.

    +
  • +

    Add value_types_of_t and error_types_of_t alias templates; rename stop_token_type_t to stop_token_of_t.

    +
  • +

    Add a design rationale for the removal of the possibly eager algorithms.

    +
  • +

    Expand the section on field experience.

    +
+

2.8. R2

+

The changes since R1 are as follows:

+
    +
  • +

    Remove the eagerly executing sender algorithms.

    +
  • +

    Extend the execution::connect customization point and the sender_traits<> template to recognize awaitables as typed_senders.

    +
  • +

    Add utilities as_awaitable() and with_awaitable_senders<> so a coroutine +type can trivially make senders awaitable with a coroutine.

    +
  • +

    Add a section describing the design of the sender/awaitable interactions.

    +
  • +

    Add a section describing the design of the cancellation support in +sender/receiver.

    +
  • +

    Add a section showing examples of simple sender adaptor algorithms.

    +
  • +

    Add a section showing examples of simple schedulers.

    +
  • +

    Add a few more examples: a sudoku solver, a parallel recursive file copy, and +an echo server.

    +
  • +

    Refined the forward progress guarantees on the bulk algorithm.

    +
  • +

    Add a section describing how to use a range of senders to represent async +sequences.

    +
  • +

    Add a section showing how to use senders to represent partial success.

    +
  • +

    Add sender factories execution::just_error and execution::just_stopped.

    +
  • +

    Add sender adaptors execution::stopped_as_optional and execution::stopped_as_error.

    +
  • +

    Document more production uses of sender/receiver at scale.

    +
  • +

    Various fixes of typos and bugs.

    +
+

2.9. R1

+

The changes since R0 are as follows:

+
    +
  • +

    Added a new concept, sender_of.

    +
  • +

    Added a new scheduler query, this_thread::execute_may_block_caller.

    +
  • +

    Added a new scheduler query, get_forward_progress_guarantee.

    +
  • +

    Removed the unschedule adaptor.

    +
  • +

    Various fixes of typos and bugs.

    +
+

2.10. R0

+

Initial revision.

+

3. Design - introduction

+

The following three sections describe the entirety of the proposed design.

+
    +
  • +

    § 3 Design - introduction describes the conventions used through the rest of the +design sections, as well as an example illustrating how we envision code +will be written using this proposal.

    +
  • +

    § 4 Design - user side describes all the functionality from the perspective we +intend for users: it describes the various concepts they will interact with, +and what their programming model is.

    +
  • +

    § 5 Design - implementer side describes the machinery that allows for that +programming model to function, and the information contained there is +necessary for people implementing senders and sender algorithms (including +the standard library ones) - but is not necessary to use senders +productively.

    +
+

3.1. Conventions

+

The following conventions are used throughout the design section:

+
    +
  1. +

    The namespace proposed in this paper is the same as in A Unified Executors Proposal for C++: std::execution; however, for brevity, the std:: part of this name is +omitted. When you see execution::foo, treat that as std::execution::foo.

    +
  2. +

    Universal references and explicit calls to std::move/std::forward are +omitted in code samples and signatures for simplicity; assume universal +references and perfect forwarding unless stated otherwise.

    +
  3. +

    None of the names proposed here are names that we are particularly attached +to; consider the names to be reasonable placeholders that can freely be +changed, should the committee want to do so.

    +
+

3.2. Queries and algorithms

+

A query is a callable that takes some set of objects (usually one) as +parameters and returns facts about those objects without modifying them. Queries +are usually customization point objects, but in some cases may be functions.

+

An algorithm is a callable that takes some set of objects as parameters and +causes those objects to do something. Algorithms are usually customization point +objects, but in some cases may be functions.

+

4. Design - user side

+

4.1. Execution resources describe the place of execution

+

An execution resource is a resource that represents the place where +execution will happen. This could be a concrete resource - like a specific +thread pool object, or a GPU - or a more abstract one, like the current thread +of execution. Execution contexts don’t need to have a representation in code; +they are simply a term describing certain properties of execution of a function.

+

4.2. Schedulers represent execution resources

+

A scheduler is a lightweight handle that represents a strategy for +scheduling work onto an execution resource. Since execution resources don’t +necessarily manifest in C++ code, it’s not possible to program directly against +their API. A scheduler is a solution to that problem: the scheduler concept is +defined by a single sender algorithm, schedule, which returns a sender that +will complete on an execution resource determined by the scheduler. Logic that +you want to run on that context can be placed in the receiver’s +completion-signalling method.

+
execution::scheduler auto sch = thread_pool.scheduler();
+execution::sender auto snd = execution::schedule(sch);
+// snd is a sender (see below) describing the creation of a new execution resource
+// on the execution resource associated with sch
+
+

Note that a particular scheduler type may provide other kinds of scheduling +operations which are supported by its associated execution resource. It is not +limited to scheduling purely using the execution::schedule API.

+

Future papers will propose additional scheduler concepts that extend scheduler to add other capabilities. For example:

+
    +
  • +

    A time_scheduler concept that extends scheduler to support time-based +scheduling. Such a concept might provide access to schedule_after(sched, duration), schedule_at(sched, time_point) and now(sched) APIs.

    +
  • +

    Concepts that extend scheduler to support opening, reading and writing files +asynchronously.

    +
  • +

    Concepts that extend scheduler to support connecting, sending data and +receiving data over the network asynchronously.

    +
+

4.3. Senders describe work

+

A sender is an object that describes work. Senders are similar to futures in +existing asynchrony designs, but unlike futures, the work that is being done to +arrive at the values they will send is also directly described by the sender +object itself. A sender is said to send some values if a receiver connected +(see § 5.3 execution::connect) to that sender will eventually receive said values.

+

The primary defining sender algorithm is § 5.3 execution::connect; this function, +however, is not a user-facing API; it is used to facilitate communication +between senders and various sender algorithms, but end user code is not expected +to invoke it directly.

+

The way user code is expected to interact with senders is by using sender +algorithms. This paper proposes an initial set of such sender algorithms, +which are described in § 4.4 Senders are composable through sender algorithms, § 4.19 User-facing sender factories, § 4.20 User-facing sender adaptors, and § 4.21 User-facing sender consumers. For example, here +is how a user can create a new sender on a scheduler, attach a continuation to +it, and then wait for execution of the continuation to complete:

+
execution::scheduler auto sch = thread_pool.scheduler();
+execution::sender auto snd = execution::schedule(sch);
+execution::sender auto cont = execution::then(snd, []{
+    std::fstream file{ "result.txt" };
+    file << compute_result;
+});
+
+this_thread::sync_wait(cont);
+// at this point, cont has completed execution
+
+

4.4. Senders are composable through sender algorithms

+

Asynchronous programming often departs from traditional code structure and +control flow that we are familiar with. A successful asynchronous framework must +provide an intuitive story for composition of asynchronous work: expressing +dependencies, passing objects, managing object lifetimes, etc.

+

The true power and utility of senders is in their composability. With senders, +users can describe generic execution pipelines and graphs, and then run them on +and across a variety of different schedulers. Senders are composed using sender algorithms:

+
    +
  • +

    sender factories, algorithms that take no senders and return a sender.

    +
  • +

    sender adaptors, algorithms that take (and potentially execution::connect) senders and return a sender.

    +
  • +

    sender consumers, algorithms that take (and potentially execution::connect) senders and do not return a sender.

    +
+

4.5. Senders can propagate completion schedulers

+

One of the goals of executors is to support a diverse set of execution +resources, including traditional thread pools, task and fiber frameworks (like HPX Legion), and GPUs and other +accelerators (managed by runtimes such as CUDA or SYCL). On many of these +systems, not all execution agents are created equal and not all functions can be +run on all execution agents. Having precise control over the execution resource +used for any given function call being submitted is important on such systems, +and the users of standard execution facilities will expect to be able to express +such requirements.

+

A Unified Executors Proposal for C++ was not always clear about the place of execution of any +given piece of code. Precise control was present in the two-way execution API +present in earlier executor designs, but it has so far been missing from the +senders design. There has been a proposal (Towards C++23 executors: A proposal for an initial set of algorithms) to provide a number of +sender algorithms that would enforce certain rules on the places of execution of +the work described by a sender, but we have found those sender algorithms to be +insufficient for achieving the best performance on all platforms that are of +interest to us. The implementation strategies that we are aware of result in one +of the following situations:

+
    +
  1. +

    trying to submit work to one execution resource (such as a CPU thread pool) + from another execution resource (such as a GPU or a task framework), which + assumes that all execution agents are as capable as a std::thread (which + they aren’t).

    +
  2. +

    forcibly interleaving two adjacent execution graph nodes that are both + executing on one execution resource (such as a GPU) with glue code that + runs on another execution resource (such as a CPU), which is prohibitively + expensive for some execution resources (such as CUDA or SYCL).

    +
  3. +

    having to customise most or all sender algorithms to support an execution + resource, so that you can avoid problems described in 1. and 2, which we + believe is impractical and brittle based on months of field experience + attempting this in Agency.

    +
+

None of these implementation strategies are acceptable for many classes of +parallel runtimes, such as task frameworks (like HPX) or accelerator runtimes (like CUDA +or SYCL).

+

Therefore, in addition to the on sender algorithm from Towards C++23 executors: A proposal for an initial set of algorithms, we are +proposing a way for senders to advertise what scheduler (and by extension what +execution resource) they will complete on. Any given sender may have completion schedulers for some or all of the signals (value, error, or +stopped) it completes with (for more detail on the completion-signals, see § 5.1 Receivers serve as glue between senders). When further work is attached to that sender by invoking +sender algorithms, that work will also complete on an appropriate completion +scheduler.

+

4.5.1. execution::get_completion_scheduler

+

get_completion_scheduler is a query that retrieves the completion scheduler +for a specific completion-signal from a sender’s environment. For a sender that +lacks a completion scheduler query for a given signal, calling get_completion_scheduler is ill-formed. If a sender advertises a completion +scheduler for a signal in this way, that sender must ensure that it sends that signal on an execution agent belonging to an execution +resource represented by a scheduler returned from this function. See § 4.5 Senders can propagate completion schedulers for more details.

+
execution::scheduler auto cpu_sched = new_thread_scheduler{};
+execution::scheduler auto gpu_sched = cuda::scheduler();
+
+execution::sender auto snd0 = execution::schedule(cpu_sched);
+execution::scheduler auto completion_sch0 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd0));
+// completion_sch0 is equivalent to cpu_sched
+
+execution::sender auto snd1 = execution::then(snd0, []{
+    std::cout << "I am running on cpu_sched!\n";
+});
+execution::scheduler auto completion_sch1 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd1));
+// completion_sch1 is equivalent to cpu_sched
+
+execution::sender auto snd2 = execution::transfer(snd1, gpu_sched);
+execution::sender auto snd3 = execution::then(snd2, []{
+    std::cout << "I am running on gpu_sched!\n";
+});
+execution::scheduler auto completion_sch3 =
+  execution::get_completion_scheduler<execution::set_value_t>(get_env(snd3));
+// completion_sch3 is equivalent to gpu_sched
+
+

4.6. Execution resource transitions are explicit

+

A Unified Executors Proposal for C++ does not contain any mechanisms for performing an execution +resource transition. The only sender algorithm that can create a sender that +will move execution to a specific execution resource is execution::schedule, +which does not take an input sender. That means that there’s no way to construct +sender chains that traverse different execution resources. This is necessary to +fulfill the promise of senders being able to replace two-way executors, which +had this capability.

+

We propose that, for senders advertising their completion scheduler, all +execution resource transitions must be explicit; running user code +anywhere but where they defined it to run must be considered a bug.

+

The execution::transfer sender adaptor performs a transition from one +execution resource to another:

+
execution::scheduler auto sch1 = ...;
+execution::scheduler auto sch2 = ...;
+
+execution::sender auto snd1 = execution::schedule(sch1);
+execution::sender auto then1 = execution::then(snd1, []{
+    std::cout << "I am running on sch1!\n";
+});
+
+execution::sender auto snd2 = execution::transfer(then1, sch2);
+execution::sender auto then2 = execution::then(snd2, []{
+    std::cout << "I am running on sch2!\n";
+});
+
+this_thread::sync_wait(then2);
+
+

4.7. Senders can be either multi-shot or single-shot

+

Some senders may only support launching their operation a single time, while others may be repeatable +and support being launched multiple times. Executing the operation may consume resources owned by the +sender.

+

For example, a sender may contain a std::unique_ptr that it will be transferring ownership of to the +operation-state returned by a call to execution::connect so that the operation has access to +this resource. In such a sender, calling execution::connect consumes the sender such that after +the call the input sender is no longer valid. Such a sender will also typically be move-only so that +it can maintain unique ownership of that resource.

+

A single-shot sender can only be connected to a receiver +at most once. Its implementation of execution::connect only has overloads for +an rvalue-qualified sender. Callers must pass the sender as an rvalue to the +call to execution::connect, indicating that the call consumes the sender.

+

A multi-shot sender can be connected to multiple +receivers and can be launched multiple times. Multi-shot senders customise execution::connect to accept an lvalue reference to the sender. Callers can +indicate that they want the sender to remain valid after the call to execution::connect by passing an lvalue reference to the sender to call these +overloads. Multi-shot senders should also define overloads of execution::connect that accept rvalue-qualified senders to allow the sender to +be also used in places where only a single-shot sender is required.

+

If the user of a sender does not require the sender to remain valid after +connecting it to a receiver then it can pass an rvalue-reference to the sender +to the call to execution::connect. Such usages should be able to accept either +single-shot or multi-shot senders.

+

If the caller does wish for the sender to remain valid after the call then it +can pass an lvalue-qualified sender to the call to execution::connect. Such +usages will only accept multi-shot senders.

+

Algorithms that accept senders will typically either decay-copy an input sender +and store it somewhere for later usage (for example as a data-member of the +returned sender) or will immediately call execution::connect on the input +sender, such as in this_thread::sync_wait or execution::start_detached.

+

Some multi-use sender algorithms may require that an input sender be +copy-constructible but will only call execution::connect on an rvalue of each +copy, which still results in effectively executing the operation multiple times. +Other multi-use sender algorithms may require that the sender is +move-constructible but will invoke execution::connect on an lvalue reference +to the sender.

+

For a sender to be usable in both multi-use scenarios, it will generally be +required to be both copy-constructible and lvalue-connectable.

+

4.8. Senders are forkable

+

Any non-trivial program will eventually want to fork a chain of senders into +independent streams of work, regardless of whether they are single-shot or +multi-shot. For instance, an incoming event to a middleware system may be +required to trigger events on more than one downstream system. This requires +that we provide well defined mechanisms for making sure that connecting a sender +multiple times is possible and correct.

+

The split sender adaptor facilitates connecting to a sender multiple times, +regardless of whether it is single-shot or multi-shot:

+
auto some_algorithm(execution::sender auto&& input) {
+    execution::sender auto multi_shot = split(input);
+    // "multi_shot" is guaranteed to be multi-shot,
+    // regardless of whether "input" was multi-shot or not
+
+    return when_all(
+      then(multi_shot, [] { std::cout << "First continuation\n"; }),
+      then(multi_shot, [] { std::cout << "Second continuation\n"; })
+    );
+}
+
+

4.9. Senders support cancellation

+

Senders are often used in scenarios where the application may be concurrently +executing multiple strategies for achieving some program goal. When one of these +strategies succeeds (or fails) it may not make sense to continue pursuing the +other strategies as their results are no longer useful.

+

For example, we may want to try to simultaneously connect to multiple network +servers and use whichever server responds first. Once the first server responds +we no longer need to continue trying to connect to the other servers.

+

Ideally, in these scenarios, we would somehow be able to request that those +other strategies stop executing promptly so that their resources (e.g. cpu, +memory, I/O bandwidth) can be released and used for other work.

+

While the design of senders has support for cancelling an operation before it +starts by simply destroying the sender or the operation-state returned from execution::connect() before calling execution::start(), there also needs to +be a standard, generic mechanism to ask for an already-started operation to +complete early.

+

The ability to be able to cancel in-flight operations is fundamental to +supporting some kinds of generic concurrency algorithms.

+

For example:

+
    +
  • +

    a when_all(ops...) algorithm should cancel other operations as soon as one +operation fails

    +
  • +

    a first_successful(ops...) algorithm should cancel the other operations as +soon as one operation completes successfuly

    +
  • +

    a generic timeout(src, duration) algorithm needs to be able to cancel the src operation after the timeout duration has elapsed.

    +
  • +

    a stop_when(src, trigger) algorithm should cancel src if trigger completes first and cancel trigger if src completes first

    +
+

The mechanism used for communcating cancellation-requests, or stop-requests, +needs to have a uniform interface so that generic algorithms that compose +sender-based operations, such as the ones listed above, are able to communicate +these cancellation requests to senders that they don’t know anything about.

+

The design is intended to be composable so that cancellation of higher-level +operations can propagate those cancellation requests through intermediate layers +to lower-level operations that need to actually respond to the cancellation +requests.

+

For example, we can compose the algorithms mentioned above so that child +operations are cancelled when any one of the multiple cancellation conditions +occurs:

+
sender auto composed_cancellation_example(auto query) {
+  return stop_when(
+    timeout(
+      when_all(
+        first_successful(
+          query_server_a(query),
+          query_server_b(query)),
+        load_file("some_file.jpg")),
+      5s),
+    cancelButton.on_click());
+}
+
+

In this example, if we take the operation returned by query_server_b(query), +this operation will receive a stop-request when any of the following happens:

+
    +
  • +

    first_successful algorithm will send a stop-request if query_server_a(query) completes successfully

    +
  • +

    when_all algorithm will send a stop-request if the load_file("some_file.jpg") operation completes with an error or stopped +result.

    +
  • +

    timeout algorithm will send a stop-request if the operation does not +complete within 5 seconds.

    +
  • +

    stop_when algorithm will send a stop-request if the user clicks on the +"Cancel" button in the user-interface.

    +
  • +

    The parent operation consuming the composed_cancellation_example() sends a +stop-request

    +
+

Note that within this code there is no explicit mention of cancellation, +stop-tokens, callbacks, etc. yet the example fully supports and responds to the +various cancellation sources.

+

The intent of the design is that the common usage of cancellation in +sender/receiver-based code is primarily through use of concurrency algorithms +that manage the detailed plumbing of cancellation for you. Much like algorithms +that compose senders relieve the user from having to write their own receiver +types, algorithms that introduce concurrency and provide higher-level +cancellation semantics relieve the user from having to deal with low-level +details of cancellation.

+

4.9.1. Cancellation design summary

+

The design of cancellation described in this paper is built on top of and +extends the std::stop_token-based cancellation facilities added in C++20, +first proposed in Composable cancellation for sender-based async operations.

+

At a high-level, the facilities proposed by this paper for supporting +cancellation include:

+
    +
  • +

    Add a std::stoppable_token concept that generalises the interface of the std::stop_token type to allow other stop token types with different +implementation strategies.

    +
  • +

    Add std::unstoppable_token concept for detecting whether a stoppable_token can never receive a stop-request.

    +
  • +

    Add std::inplace_stop_token, std::inplace_stop_source and std::inplace_stop_callback<CB> types that provide a more efficient +implementation of a stop-token for use in structured concurrency situations.

    +
  • +

    Add std::never_stop_token for use in places where you never want to issue a +stop-request.

    +
  • +

    Add std::execution::get_stop_token() CPO for querying the stop-token to use +for an operation from its receiver’s execution environment.

    +
  • +

    Add std::execution::stop_token_of_t<T> for querying the type of a stop-token +returned from get_stop_token().

    +
+

In addition, there are requirements added to some of the algorithms to specify +what their cancellation behaviour is and what the requirements of customisations +of those algorithms are with respect to cancellation.

+

The key component that enables generic cancellation within sender-based +operations is the execution::get_stop_token() CPO. This CPO takes a single +parameter, which is the execution environment of the receiver passed to execution::connect, and returns a std::stoppable_token that the operation +can use to check for stop-requests for that operation.

+

As the caller of execution::connect typically has control over the receiver +type it passes, it is able to customise the std::execution::get_env() CPO for +that receiver to return an execution environment that hooks the execution::get_stop_token() CPO to return a stop-token that the receiver has +control over and that it can use to communicate a stop-request to the operation +once it has started.

+

4.9.2. Support for cancellation is optional

+

Support for cancellation is optional, both on part of the author of the receiver +and on part of the author of the sender.

+

If the receiver’s execution environment does not customise the execution::get_stop_token() CPO then invoking the CPO on that receiver’s +environment will invoke the default implementation which returns std::never_stop_token. This is a special stoppable_token type that is +statically known to always return false from the stop_possible() method.

+

Sender code that tries to use this stop-token will in general result in code +that handles stop-requests being compiled out and having little to no run-time +overhead.

+

If the sender doesn’t call execution::get_stop_token(), for example because +the operation does not support cancellation, then it will simply not respond to +stop-requests from the caller.

+

Note that stop-requests are generally racy in nature as there is often a race +betwen an operation completing naturally and the stop-request being made. If the +operation has already completed or past the point at which it can be cancelled +when the stop-request is sent then the stop-request may just be ignored. An +application will typically need to be able to cope with senders that might +ignore a stop-request anyway.

+

4.9.3. Cancellation is inherently racy

+

Usually, an operation will attach a stop-callback at some point inside the call +to execution::start() so that a subsequent stop-request will interrupt the +logic.

+

A stop-request can be issued concurrently from another thread. This means the +implementation of execution::start() needs to be careful to ensure that, once +a stop-callback has been registered, that there are no data-races between a +potentially concurrently-executing stop-callback and the rest of the execution::start() implementation.

+

An implementation of execution::start() that supports cancellation will +generally need to perform (at least) two separate steps: launch the operation, +subscribe a stop-callback to the receiver’s stop-token. Care needs to be taken +depending on the order in which these two steps are performed.

+

If the stop-callback is subscribed first and then the operation is launched, +care needs to be taken to ensure that a stop-request that invokes the +stop-callback on another thread after the stop-callback is registered but before +the operation finishes launching does not either result in a missed cancellation +request or a data-race. e.g. by performing an atomic write after the launch has +finished executing

+

If the operation is launched first and then the stop-callback is subscribed, +care needs to be taken to ensure that if the launched operation completes +concurrently on another thread that it does not destroy the operation-state +until after the stop-callback has been registered. e.g. by having the execution::start implementation write to an atomic variable once it has +finished registering the stop-callback and having the concurrent completion +handler check that variable and either call the completion-signalling operation +or store the result and defer calling the receiver’s completion-signalling +operation to the execution::start() call (which is still executing).

+

For an example of an implementation strategy for solving these data-races see § 1.4 Asynchronous Windows socket recv.

+

4.9.4. Cancellation design status

+

This paper currently includes the design for cancellation as proposed in Composable cancellation for sender-based async operations - "Composable cancellation for sender-based async operations". +P2175R0 contains more details on the background motivation and prior-art and +design rationale of this design.

+

It is important to note, however, that initial review of this design in the SG1 +concurrency subgroup raised some concerns related to runtime overhead of the +design in single-threaded scenarios and these concerns are still being +investigated.

+

The design of P2175R0 has been included in this paper for now, despite its +potential to change, as we believe that support for cancellation is a +fundamental requirement for an async model and is required in some form to be +able to talk about the semantics of some of the algorithms proposed in this +paper.

+

This paper will be updated in the future with any changes that arise from the +investigations into P2175R0.

+

4.10. Sender factories and adaptors are lazy

+

In an earlier revision of this paper, some of the proposed algorithms supported +executing their logic eagerly; i.e., before the returned sender has been +connected to a receiver and started. These algorithms were removed because eager +execution has a number of negative semantic and performance implications.

+

We have originally included this functionality in the paper because of a +long-standing belief that eager execution is a mandatory feature to be included +in the standard Executors facility for that facility to be acceptable for +accelerator vendors. A particular concern was that we must be able to write +generic algorithms that can run either eagerly or lazily, depending on the kind +of an input sender or scheduler that have been passed into them as arguments. We +considered this a requirement, because the _latency_ of launching work on an +accelerator can sometimes be considerable.

+

However, in the process of working on this paper and implementations of the +features proposed within, our set of requirements has shifted, as we understood +the different implementation strategies that are available for the feature set +of this paper better, and, after weighting the earlier concerns against the +points presented below, we have arrived at the conclusion that a purely lazy +model is enough for most algorithms, and users who intend to launch work earlier +may use an algorithm such as ensure_started to achieve that goal. We have also +come to deeply appreciate the fact that a purely lazy model allows both the +implementation and the compiler to have a much better understanding of what the +complete graph of tasks looks like, allowing them to better optimize the code - +also when targetting accelerators.

+

4.10.1. Eager execution leads to detached work or worse

+

One of the questions that arises with APIs that can potentially return +eagerly-executing senders is "What happens when those senders are destructed +without a call to execution::connect?" or similarly, "What happens if a call +to execution::connect is made, but the returned operation state is destroyed +before execution::start is called on that operation state"?

+

In these cases, the operation represented by the sender is potentially executing +concurrently in another thread at the time that the destructor of the sender +and/or operation-state is running. In the case that the operation has not +completed executing by the time that the destructor is run we need to decide +what the semantics of the destructor is.

+

There are three main strategies that can be adopted here, none of which is +particularly satisfactory:

+
    +
  1. +

    Make this undefined-behaviour - the caller must ensure that any +eagerly-executing sender is always joined by connecting and starting that +sender. This approach is generally pretty hostile to programmers, +particularly in the presence of exceptions, since it complicates the ability +to compose these operations.

    +

    Eager operations typically need to acquire resources when they are first +called in order to start the operation early. This makes eager algorithms +prone to failure. Consider, then, what might happen in an expression such as when_all(eager_op_1(), eager_op_2()). Imagine eager_op_1() starts an +asynchronous operation successfully, but then eager_op_2() throws. For +lazy senders, that failure happens in the context of the when_all algorithm, which handles the failure and ensures that async work joins on +all code paths. In this case though -- the eager case -- the child operation +has failed even before when_all has been called.

    +

    It then becomes the responsibility, not of the algorithm, but of the end +user to handle the exception and ensure that eager_op_1() is joined before +allowing the exception to propagate. If they fail to do that, they incur +undefined behavior.

    +
  2. +

    Detach from the computation - let the operation continue in the background - +like an implicit call to std::thread::detach(). While this approach can +work in some circumstances for some kinds of applications, in general it is +also pretty user-hostile; it makes it difficult to reason about the safe +destruction of resources used by these eager operations. In general, +detached work necessitates some kind of garbage collection; e.g., std::shared_ptr, to ensure resources are kept alive until the operations +complete, and can make clean shutdown nigh impossible.

    +
  3. +

    Block in the destructor until the operation completes. This approach is +probably the safest to use as it preserves the structured nature of the +concurrent operations, but also introduces the potential for deadlocking the +application if the completion of the operation depends on the current thread +making forward progress.

    +

    The risk of deadlock might occur, for example, if a thread-pool with a +small number of threads is executing code that creates a sender representing +an eagerly-executing operation and then calls the destructor of that sender +without joining it (e.g. because an exception was thrown). If the current +thread blocks waiting for that eager operation to complete and that eager +operation cannot complete until some entry enqueued to the thread-pool’s +queue of work is run then the thread may wait for an indefinite amount of +time. If all threads of the thread-pool are simultaneously performing such +blocking operations then deadlock can result.

    +
+

There are also minor variations on each of these choices. For example:

+
    +
  1. +

    A variation of (1): Call std::terminate if an eager sender is destructed +without joining it. This is the approach that std::thread destructor +takes.

    +
  2. +

    A variation of (2): Request cancellation of the operation before detaching. +This reduces the chances of operations continuing to run indefinitely in the +background once they have been detached but does not solve the +lifetime- or shutdown-related challenges.

    +
  3. +

    A variation of (3): Request cancellation of the operation before blocking on +its completion. This is the strategy that std::jthread uses for its +destructor. It reduces the risk of deadlock but does not eliminate it.

    +
+

4.10.2. Eager senders complicate algorithm implementations

+

Algorithms that can assume they are operating on senders with strictly lazy +semantics are able to make certain optimizations that are not available if +senders can be potentially eager. With lazy senders, an algorithm can safely +assume that a call to execution::start on an operation state strictly happens +before the execution of that async operation. This frees the algorithm from +needing to resolve potential race conditions. For example, consider an algorithm sequence that puts async operations in sequence by starting an operation only +after the preceding one has completed. In an expression like sequence(a(), then(src, [] { b(); }), c()), one may reasonably assume that a(), b() and c() are sequenced and therefore do not need synchronisation. Eager algorithms +break that assumption.

+

When an algorithm needs to deal with potentially eager senders, the potential +race conditions can be resolved one of two ways, neither of which is desirable:

+
    +
  1. +

    Assume the worst and implement the algorithm defensively, assuming all +senders are eager. This obviously has overheads both at runtime and in +algorithm complexity. Resolving race conditions is hard.

    +
  2. +

    Require senders to declare whether they are eager or not with a query. +Algorithms can then implement two different implementation strategies, one +for strictly lazy senders and one for potentially eager senders. This +addresses the performance problem of (1) while compounding the complexity +problem.

    +
+

4.10.3. Eager senders incur cancellation-related overhead

+

Another implication of the use of eager operations is with regards to +cancellation. The eagerly executing operation will not have access to the +caller’s stop token until the sender is connected to a receiver. If we still +want to be able to cancel the eager operation then it will need to create a new +stop source and pass its associated stop token down to child operations. Then +when the returned sender is eventually connected it will register a stop +callback with the receiver’s stop token that will request stop on the eager +sender’s stop source.

+

As the eager operation does not know at the time that it is launched what the +type of the receiver is going to be, and thus whether or not the stop token +returned from execution::get_stop_token is an std::unstoppable_token or not, +the eager operation is going to need to assume it might be later connected to a +receiver with a stop token that might actually issue a stop request. Thus it +needs to declare space in the operation state for a type-erased stop callback +and incur the runtime overhead of supporting cancellation, even if cancellation +will never be requested by the caller.

+

The eager operation will also need to do this to support sending a stop request +to the eager operation in the case that the sender representing the eager work +is destroyed before it has been joined (assuming strategy (5) or (6) listed +above is chosen).

+

4.10.4. Eager senders cannot access execution resource from the receiver

+

In sender/receiver, contextual information is passed from parent operations to +their children by way of receivers. Information like stop tokens, allocators, +current scheduler, priority, and deadline are propagated to child operations +with custom receivers at the time the operation is connected. That way, each +operation has the contextual information it needs before it is started.

+

But if the operation is started before it is connected to a receiver, then there +isn’t a way for a parent operation to communicate contextual information to its +child operations, which may complete before a receiver is ever attached.

+

4.11. Schedulers advertise their forward progress guarantees

+

To decide whether a scheduler (and its associated execution resource) is +sufficient for a specific task, it may be necessary to know what kind of forward +progress guarantees it provides for the execution agents it creates. The C++ +Standard defines the following forward progress guarantees:

+
    +
  • +

    concurrent, which requires that a thread makes progress eventually;

    +
  • +

    parallel, which requires that a thread makes progress once it executes +a step; and

    +
  • +

    weakly parallel, which does not require that the thread makes progress.

    +
+

This paper introduces a scheduler query function, get_forward_progress_guarantee, which returns one of the enumerators of a new enum type, forward_progress_guarantee. Each enumerator of forward_progress_guarantee corresponds to one of the aforementioned +guarantees.

+

4.12. Most sender adaptors are pipeable

+

To facilitate an intuitive syntax for composition, most sender adaptors are pipeable; they can be composed (piped) +together with operator|. This mechanism is similar to the operator| composition that C++ range adaptors support and draws inspiration from piping in +*nix shells. +Pipeable sender adaptors take a sender as their first parameter and have no +other sender parameters.

+

a | b will pass the sender a as the first argument to the pipeable sender +adaptor b. Pipeable sender adaptors support partial application of the +parameters after the first. For example, all of the following are equivalent:

+
execution::bulk(snd, N, [] (std::size_t i, auto d) {});
+execution::bulk(N, [] (std::size_t i, auto d) {})(snd);
+snd | execution::bulk(N, [] (std::size_t i, auto d) {});
+
+

Piping enables you to compose together senders with a linear syntax. Without it, +you’d have to use either nested function call syntax, which would cause a +syntactic inversion of the direction of control flow, or you’d have to introduce +a temporary variable for each stage of the pipeline. Consider the following +example where we want to execute first on a CPU thread pool, then on a CUDA GPU, +then back on the CPU thread pool:

+ + + + + + +
Syntax Style + Example +
Function call
(nested) +
+
auto snd = execution::then(
+             execution::transfer(
+               execution::then(
+                 execution::transfer(
+                   execution::then(
+                     execution::schedule(thread_pool.scheduler())
+                     []{ return 123; }),
+                   cuda::new_stream_scheduler()),
+                 [](int i){ return 123 * 5; }),
+               thread_pool.scheduler()),
+             [](int i){ return i - 5; });
+auto [result] = this_thread::sync_wait(snd).value();
+// result == 610
+
+
Function call
(named temporaries) +
+
auto snd0 = execution::schedule(thread_pool.scheduler());
+auto snd1 = execution::then(snd0, []{ return 123; });
+auto snd2 = execution::transfer(snd1, cuda::new_stream_scheduler());
+auto snd3 = execution::then(snd2, [](int i){ return 123 * 5; })
+auto snd4 = execution::transfer(snd3, thread_pool.scheduler())
+auto snd5 = execution::then(snd4, [](int i){ return i - 5; });
+auto [result] = *this_thread::sync_wait(snd4);
+// result == 610
+
+
Pipe + +
auto snd = execution::schedule(thread_pool.scheduler())
+         | execution::then([]{ return 123; })
+         | execution::transfer(cuda::new_stream_scheduler())
+         | execution::then([](int i){ return 123 * 5; })
+         | execution::transfer(thread_pool.scheduler())
+         | execution::then([](int i){ return i - 5; });
+auto [result] = this_thread::sync_wait(snd).value();
+// result == 610
+
+
+

Certain sender adaptors are not pipeable, because using the pipeline syntax can +result in confusion of the semantics of the adaptors involved. Specifically, the +following sender adaptors are not pipeable.

+
    +
  • +

    execution::when_all and execution::when_all_with_variant: Since this +sender adaptor takes a variadic pack of senders, a partially applied form +would be ambiguous with a non partially applied form with an arity of one +less.

    +
  • +

    execution::on: This sender adaptor changes how the sender passed to it is +executed, not what happens to its result, but allowing it in a pipeline makes +it read as if it performed a function more similar to transfer.

    +
+

Sender consumers could be made pipeable, but we have chosen to not do so. +However, since these are terminal nodes in a pipeline and nothing can be piped +after them, we believe a pipe syntax may be confusing as well as unnecessary, as +consumers cannot be chained. We believe sender consumers read better with +function call syntax.

+

4.13. A range of senders represents an async sequence of data

+

Senders represent a single unit of asynchronous work. In many cases though, what +is being modeled is a sequence of data arriving asynchronously, and you want +computation to happen on demand, when each element arrives. This requires +nothing more than what is in this paper and the range support in C++20. A range +of senders would allow you to model such input as keystrikes, mouse movements, +sensor readings, or network requests.

+

Given some expression R that is a range of senders, consider +the following in a coroutine that returns an async generator type:

+
for (auto snd : R) {
+  if (auto opt = co_await execution::stopped_as_optional(std::move(snd)))
+    co_yield fn(*std::move(opt));
+  else
+    break;
+}
+
+

This transforms each element of the asynchronous sequence R with the function fn on demand, as the data arrives. The result is a new +asynchronous sequence of the transformed values.

+

Now imagine that R is the simple expression views::iota(0) | views::transform(execution::just). This creates a lazy range of senders, each +of which completes immediately with monotonically increasing integers. The above +code churns through the range, generating a new infine asynchronous range of +values [fn(0), fn(1), fn(2), ...].

+

Far more interesting would be if R were a range of senders +representing, say, user actions in a UI. The above code gives a simple way to +respond to user actions on demand.

+

4.14. Senders can represent partial success

+

Receivers have three ways they can complete: with success, failure, or +cancellation. This begs the question of how they can be used to represent async +operations that partially succeed. For example, consider an API that reads +from a socket. The connection could drop after the API has filled in some of the +buffer. In cases like that, it makes sense to want to report both that the +connection dropped and that some data has been successfully read.

+

Often in the case of partial success, the error condition is not fatal nor does +it mean the API has failed to satisfy its post-conditions. It is merely an extra +piece of information about the nature of the completion. In those cases, +"partial success" is another way of saying "success". As a result, it is +sensible to pass both the error code and the result (if any) through the value +channel, as shown below:

+
// Capture a buffer for read_socket_async to fill in
+execution::just(array<byte, 1024>{})
+  | execution::let_value([socket](array<byte, 1024>& buff) {
+      // read_socket_async completes with two values: an error_code and
+      // a count of bytes:
+      return read_socket_async(socket, span{buff})
+          // For success (partial and full), specify the next action:
+        | execution::let_value([](error_code err, size_t bytes_read) {
+            if (err != 0) {
+              // OK, partial success. Decide how to deal with the partial results
+            } else {
+              // OK, full success here.
+            }
+          });
+    })
+
+

In other cases, the partial success is more of a partial failure. That happens +when the error condition indicates that in some way the function failed to +satisfy its post-conditions. In those cases, sending the error through the value +channel loses valuable contextual information. It’s possible that bundling the +error and the incomplete results into an object and passing it through the error +channel makes more sense. In that way, generic algorithms will not miss the fact +that a post-condition has not been met and react inappropriately.

+

Another possibility is for an async API to return a range of senders: if the +API completes with full success, full error, or cancellation, the returned range +contains just one sender with the result. Otherwise, if the API partially fails +(doesn’t satisfy its post-conditions, but some incomplete result is available), +the returned range would have two senders: the first containing the partial +result, and the second containing the error. Such an API might be used in a +coroutine as follows:

+
// Declare a buffer for read_socket_async to fill in
+array<byte, 1024> buff;
+
+for (auto snd : read_socket_async(socket, span{buff})) {
+  try {
+    if (optional<size_t> bytes_read =
+          co_await execution::stopped_as_optional(std::move(snd))) {
+      // OK, we read some bytes into buff. Process them here....
+    } else {
+      // The socket read was cancelled and returned no data. React
+      // appropriately.
+    }
+  } catch (...) {
+    // read_socket_async failed to meet its post-conditions.
+    // Do some cleanup and propagate the error...
+  }
+}
+
+

Finally, it’s possible to combine these two approaches when the API can both +partially succeed (meeting its post-conditions) and partially fail (not meeting +its post-conditions).

+

4.15. All awaitables are senders

+

Since C++20 added coroutines to the standard, we expect that coroutines and +awaitables will be how a great many will choose to express their asynchronous +code. However, in this paper, we are proposing to add a suite of asynchronous +algorithms that accept senders, not awaitables. One might wonder whether and how +these algorithms will be accessible to those who choose coroutines instead of +senders.

+

In truth there will be no problem because all generally awaitable types +automatically model the sender concept. The adaptation is transparent and +happens in the sender customization points, which are aware of awaitables. (By +"generally awaitable" we mean types that don’t require custom await_transform trickery from a promise type to make them awaitable.)

+

For an example, imagine a coroutine type called task<T> that knows nothing +about senders. It doesn’t implement any of the sender customization points. +Despite that fact, and despite the fact that the this_thread::sync_wait algorithm is constrained with the sender concept, the following would compile +and do what the user wants:

+
task<int> doSomeAsyncWork();
+
+int main() {
+  // OK, awaitable types satisfy the requirements for senders:
+  auto o = this_thread::sync_wait(doSomeAsyncWork());
+}
+
+

Since awaitables are senders, writing a sender-based asynchronous algorithm is +trivial if you have a coroutine task type: implement the algorithm as a +coroutine. If you are not bothered by the possibility of allocations and +indirections as a result of using coroutines, then there is no need to ever +write a sender, a receiver, or an operation state.

+

4.16. Many senders can be trivially made awaitable

+

If you choose to implement your sender-based algorithms as coroutines, you’ll +run into the issue of how to retrieve results from a passed-in sender. This is +not a problem. If the coroutine type opts in to sender support -- trivial with +the execution::with_awaitable_senders utility -- then a large class of senders +are transparently awaitable from within the coroutine.

+

For example, consider the following trivial implementation of the sender-based retry algorithm:

+
template<class S>
+  requires single-sender<S&> // see [exec.as.awaitable]
+task<single-sender-value-type<S>> retry(S s) {
+  for (;;) {
+    try {
+      co_return co_await s;
+    } catch(...) {
+    }
+  }
+}
+
+

Only some senders can be made awaitable directly because of the fact that +callbacks are more expressive than coroutines. An awaitable expression has a +single type: the result value of the async operation. In contrast, a callback +can accept multiple arguments as the result of an operation. What’s more, the +callback can have overloaded function call signatures that take different sets +of arguments. There is no way to automatically map such senders into awaitables. +The with_awaitable_senders utility recognizes as awaitables those senders that +send a single value of a single type. To await another kind of sender, a user +would have to first map its value channel into a single value of a single type +-- say, with the into_variant sender algorithm -- before co_await-ing that +sender.

+

4.17. Cancellation of a sender can unwind a stack of coroutines

+

When looking at the sender-based retry algorithm in the previous section, we +can see that the value and error cases are correctly handled. But what about +cancellation? What happens to a coroutine that is suspended awaiting a sender +that completes by calling execution::set_stopped?

+

When your task type’s promise inherits from with_awaitable_senders, what +happens is this: the coroutine behaves as if an uncatchable exception had been +thrown from the co_await expression. (It is not really an exception, but it’s +helpful to think of it that way.) Provided that the promise types of the calling +coroutines also inherit from with_awaitable_senders, or more generally +implement a member function called unhandled_stopped, the exception unwinds +the chain of coroutines as if an exception were thrown except that it bypasses catch(...) clauses.

+

In order to "catch" this uncatchable stopped exception, one of the calling +coroutines in the stack would have to await a sender that maps the stopped +channel into either a value or an error. That is achievable with the execution::let_stopped, execution::upon_stopped, execution::stopped_as_optional, or execution::stopped_as_error sender +adaptors. For instance, we can use execution::stopped_as_optional to "catch" +the stopped signal and map it into an empty optional as shown below:

+
if (auto opt = co_await execution::stopped_as_optional(some_sender)) {
+  // OK, some_sender completed successfully, and opt contains the result.
+} else {
+  // some_sender completed with a cancellation signal.
+}
+
+

As described in the section "All +awaitables are senders", the sender customization points recognize +awaitables and adapt them transparently to model the sender concept. When connect-ing an awaitable and a receiver, the adaptation layer awaits the +awaitable within a coroutine that implements unhandled_stopped in its promise +type. The effect of this is that an "uncatchable" stopped exception propagates +seamlessly out of awaitables, causing execution::set_stopped to be called on +the receiver.

+

Obviously, unhandled_stopped is a library extension of the coroutine promise +interface. Many promise types will not implement unhandled_stopped. When an +uncatchable stopped exception tries to propagate through such a coroutine, it is +treated as an unhandled exception and terminate is called. The solution, as +described above, is to use a sender adaptor to handle the stopped exception +before awaiting it. It goes without saying that any future Standard Library +coroutine types ought to implement unhandled_stopped. The author of Add lazy coroutine (coroutine task) type, which proposes a standard coroutine task type, is in agreement.

+

4.18. Composition with parallel algorithms

+

The C++ Standard Library provides a large number of algorithms that offer the +potential for non-sequential execution via the use of execution policies. The +set of algorithms with execution policy overloads are often referred to as +"parallel algorithms", although additional policies are available.

+

Existing policies, such as execution::par, give the implementation permission +to execute the algorithm in parallel. However, the choice of execution resources +used to perform the work is left to the implementation.

+

We will propose a customization point for combining schedulers with policies in +order to provide control over where work will execute.

+
template<class ExecutionPolicy>
+unspecified executing_on(
+    execution::scheduler auto scheduler,
+    ExecutionPolicy && policy
+);
+
+

This function would return an object of an unspecified type which can be used in +place of an execution policy as the first argument to one of the parallel +algorithms. The overload selected by that object should execute its computation +as requested by policy while using scheduler to create any work to be run. +The expression may be ill-formed if scheduler is not able to support the given +policy.

+

The existing parallel algorithms are synchronous; all of the effects performed +by the computation are complete before the algorithm returns to its caller. This +remains unchanged with the executing_on customization point.

+

In the future, we expect additional papers will propose asynchronous forms of +the parallel algorithms which (1) return senders rather than values or void and (2) where a customization point pairing a sender with an execution policy +would similarly be used to obtain an object of unspecified type to be provided +as the first argument to the algorithm.

+

4.19. User-facing sender factories

+

A sender factory is an algorithm that takes no senders as parameters and +returns a sender.

+

4.19.1. execution::schedule

+
execution::sender auto schedule(
+    execution::scheduler auto scheduler
+);
+
+

Returns a sender describing the start of a task graph on the provided scheduler. +See § 4.2 Schedulers represent execution resources.

+
execution::scheduler auto sch1 = get_system_thread_pool().scheduler();
+
+execution::sender auto snd1 = execution::schedule(sch1);
+// snd1 describes the creation of a new task on the system thread pool
+
+

4.19.2. execution::just

+
execution::sender auto just(
+    auto ...&& values
+);
+
+

Returns a sender with no completion schedulers, which sends the provided values. The input values are decay-copied into the +returned sender. When the returned sender is connected to a receiver, the values +are moved into the operation state if the sender is an rvalue; otherwise, they +are copied. Then xvalues referencing the values in the operation state are +passed to the receiver’s set_value.

+
execution::sender auto snd1 = execution::just(3.14);
+execution::sender auto then1 = execution::then(snd1, [] (double d) {
+  std::cout << d << "\n";
+});
+
+execution::sender auto snd2 = execution::just(3.14, 42);
+execution::sender auto then2 = execution::then(snd2, [] (double d, int i) {
+  std::cout << d << ", " << i << "\n";
+});
+
+std::vector v3{1, 2, 3, 4, 5};
+execution::sender auto snd3 = execution::just(v3);
+execution::sender auto then3 = execution::then(snd3, [] (std::vector<int>&& v3copy) {
+  for (auto&& e : v3copy) { e *= 2; }
+  return std::move(v3copy);
+}
+auto&& [v3copy] = this_thread::sync_wait(then3).value();
+// v3 contains {1, 2, 3, 4, 5}; v3copy will contain {2, 4, 6, 8, 10}.
+
+execution::sender auto snd4 = execution::just(std::vector{1, 2, 3, 4, 5});
+execution::sender auto then4 = execution::then(std::move(snd4), [] (std::vector<int>&& v4) {
+  for (auto&& e : v4) { e *= 2; }
+  return std::move(v4);
+});
+auto&& [v4] = this_thread::sync_wait(std::move(then4)).value();
+// v4 contains {2, 4, 6, 8, 10}. No vectors were copied in this example.
+
+

4.19.3. execution::just_error

+
execution::sender auto just_error(
+    auto && error
+);
+
+

Returns a sender with no completion schedulers, which +completes with the specified error. If the provided error is an lvalue +reference, a copy is made inside the returned sender and a non-const lvalue +reference to the copy is sent to the receiver’s set_error. If the provided +value is an rvalue reference, it is moved into the returned sender and an rvalue +reference to it is sent to the receiver’s set_error.

+

4.19.4. execution::just_stopped

+
execution::sender auto just_stopped();
+
+

Returns a sender with no completion schedulers, which +completes immediately by calling the receiver’s set_stopped.

+

4.19.5. execution::read

+
execution::sender auto read(auto tag);
+
+execution::sender auto get_scheduler() {
+  return read(execution::get_scheduler);
+}
+execution::sender auto get_delegatee_scheduler() {
+  return read(execution::get_delegatee_scheduler);
+}
+execution::sender auto get_allocator() {
+  return read(execution::get_allocator);
+}
+execution::sender auto get_stop_token() {
+  return read(execution::get_stop_token);
+}
+
+

Returns a sender that reaches into a receiver’s environment and pulls out the +current value associated with the customization point denoted by Tag. It then +sends the value read back to the receiver through the value channel. For +instance, get_scheduler() (with no arguments) is a sender that asks the +receiver for the currently suggested scheduler and passes it to the receiver’s set_value completion-signal.

+

This can be useful when scheduling nested dependent work. The following sender +pulls the current schduler into the value channel and then schedules more work +onto it.

+
execution::sender auto task =
+  execution::get_scheduler()
+    | execution::let_value([](auto sched) {
+        return execution::on(sched, some nested work here);
+    });
+
+this_thread::sync_wait( std::move(task) ); // wait for it to finish
+
+

This code uses the fact that sync_wait associates a scheduler with the +receiver that it connects with task. get_scheduler() reads that scheduler +out of the receiver, and passes it to let_value's receiver’s set_value function, which in turn passes it to the lambda. That lambda returns a new +sender that uses the scheduler to schedule some nested work onto sync_wait's +scheduler.

+

4.20. User-facing sender adaptors

+

A sender adaptor is an algorithm that takes one or more senders, which it +may execution::connect, as parameters, and returns a sender, whose completion +is related to the sender arguments it has received.

+

Sender adaptors are lazy, that is, they are never allowed to submit any +work for execution prior to the returned sender being started later on, and +are also guaranteed to not start any input senders passed into them. Sender +consumers such as § 4.21.1 execution::start_detached and § 4.21.2 this_thread::sync_wait start senders.

+

For more implementer-centric description of starting senders, see § 5.5 Sender adaptors are lazy.

+

4.20.1. execution::transfer

+
execution::sender auto transfer(
+    execution::sender auto input,
+    execution::scheduler auto scheduler
+);
+
+

Returns a sender describing the transition from the execution agent of the input +sender to the execution agent of the target scheduler. See § 4.6 Execution resource transitions are explicit.

+
execution::scheduler auto cpu_sched = get_system_thread_pool().scheduler();
+execution::scheduler auto gpu_sched = cuda::scheduler();
+
+execution::sender auto cpu_task = execution::schedule(cpu_sched);
+// cpu_task describes the creation of a new task on the system thread pool
+
+execution::sender auto gpu_task = execution::transfer(cpu_task, gpu_sched);
+// gpu_task describes the transition of the task graph described by cpu_task to the gpu
+
+

4.20.2. execution::then

+
execution::sender auto then(
+    execution::sender auto input,
+    std::invocable<values-sent-by(input)...> function
+);
+
+

then returns a sender describing the task graph described by the input sender, +with an added node of invoking the provided function with the values sent by the input sender as arguments.

+

then is guaranteed to not begin executing function until the returned +sender is started.

+
execution::sender auto input = get_input();
+execution::sender auto snd = execution::then(input, [](auto... args) {
+    std::print(args...);
+});
+// snd describes the work described by pred
+// followed by printing all of the values sent by pred
+
+

This adaptor is included as it is necessary for writing any sender code that +actually performs a useful function.

+

4.20.3. execution::upon_*

+
execution::sender auto upon_error(
+    execution::sender auto input,
+    std::invocable<errors-sent-by(input)...> function
+);
+
+execution::sender auto upon_stopped(
+    execution::sender auto input,
+    std::invocable auto function
+);
+
+

upon_error and upon_stopped are similar to then, but where then works +with values sent by the input sender, upon_error works with errors, and upon_stopped is invoked when the "stopped" signal is sent.

+

4.20.4. execution::let_*

+
execution::sender auto let_value(
+    execution::sender auto input,
+    std::invocable<values-sent-by(input)...> function
+);
+
+execution::sender auto let_error(
+    execution::sender auto input,
+    std::invocable<errors-sent-by(input)...> function
+);
+
+execution::sender auto let_stopped(
+    execution::sender auto input,
+    std::invocable auto function
+);
+
+

let_value is very similar to then: when it is started, it invokes the +provided function with the values sent by the input sender as +arguments. However, where the sender returned from then sends exactly what +that function ends up returning - let_value requires that the function return a sender, and the sender returned +by let_value sends the values sent by the sender returned from the callback. +This is similar to the notion of "future unwrapping" in future/promise-based +frameworks.

+

let_value is guaranteed to not begin executing function until the +returned sender is started.

+

let_error and let_stopped are similar to let_value, but where let_value works with values sent by the input sender, let_error works with errors, and let_stopped is invoked when the "stopped" signal is sent.

+

4.20.5. execution::on

+
execution::sender auto on(
+    execution::scheduler auto sched,
+    execution::sender auto snd
+);
+
+

Returns a sender which, when started, will start the provided sender on an +execution agent belonging to the execution resource associated with the provided +scheduler. This returned sender has no completion +schedulers.

+

4.20.6. execution::into_variant

+
execution::sender auto into_variant(
+    execution::sender auto snd
+);
+
+

Returns a sender which sends a variant of tuples of all the possible sets of +types sent by the input sender. Senders can send multiple sets of values +depending on runtime conditions; this is a helper function that turns them into +a single variant value.

+

4.20.7. execution::stopped_as_optional

+
execution::sender auto stopped_as_optional(
+    single-sender auto snd
+);
+
+

Returns a sender that maps the value channel from a T to an optional<decay_t<T>>, and maps the stopped channel to a value of an empty optional<decay_t<T>>.

+

4.20.8. execution::stopped_as_error

+
template<move_constructible Error>
+execution::sender auto stopped_as_error(
+    execution::sender auto snd,
+    Error err
+);
+
+

Returns a sender that maps the stopped channel to an error of err.

+

4.20.9. execution::bulk

+
execution::sender auto bulk(
+    execution::sender auto input,
+    std::integral auto shape,
+    invocable<decltype(size), values-sent-by(input)...> function
+);
+
+

Returns a sender describing the task of invoking the provided function with +every index in the provided shape along with the values sent by the input +sender. The returned sender completes once all invocations have completed, or an +error has occurred. If it completes by sending values, they are equivalent to +those sent by the input sender.

+

No instance of function will begin executing until the returned sender is +started. Each invocation of function runs in an execution agent whose forward +progress guarantees are determined by the scheduler on which they are run. All +agents created by a single use of bulk execute with the same guarantee. The +number of execution agents used by bulk is not specified. This allows a +scheduler to execute some invocations of the function in parallel.

+

In this proposal, only integral types are used to specify the shape of the bulk +section. We expect that future papers may wish to explore extensions of the +interface to explore additional kinds of shapes, such as multi-dimensional +grids, that are commonly used for parallel computing tasks.

+

4.20.10. execution::split

+
execution::sender auto split(execution::sender auto sender);
+
+

If the provided sender is a multi-shot sender, returns that sender. Otherwise, +returns a multi-shot sender which sends values equivalent to the values sent by +the provided sender. See § 4.7 Senders can be either multi-shot or single-shot.

+

4.20.11. execution::when_all

+
execution::sender auto when_all(
+    execution::sender auto ...inputs
+);
+
+execution::sender auto when_all_with_variant(
+    execution::sender auto ...inputs
+);
+
+

when_all returns a sender that completes once all of the input senders have +completed. It is constrained to only accept senders that can complete with a +single set of values (_i.e._, it only calls one overload of set_value on its +receiver). The values sent by this sender are the values sent by each of the +input senders, in order of the arguments passed to when_all. It completes +inline on the execution resource on which the last input sender completes, +unless stop is requested before when_all is started, in which case it +completes inline within the call to start.

+

when_all_with_variant does the same, but it adapts all the input senders using into_variant, and so it does not constrain the input arguments as when_all does.

+

The returned sender has no completion schedulers.

+
execution::scheduler auto sched = thread_pool.scheduler();
+
+execution::sender auto sends_1 = ...;
+execution::sender auto sends_abc = ...;
+
+execution::sender auto both = execution::when_all(sched,
+    sends_1,
+    sends_abc
+);
+
+execution::sender auto final = execution::then(both, [](auto... args){
+    std::cout << std::format("the two args: {}, {}", args...);
+});
+// when final executes, it will print "the two args: 1, abc"
+
+

4.20.12. execution::ensure_started

+
execution::sender auto ensure_started(
+    execution::sender auto sender
+);
+
+

Once ensure_started returns, it is known that the provided sender has been connected and start has been called on the resulting operation +state (see § 5.2 Operation states represent work); in other words, the work described by the +provided sender has been submitted +for execution on the appropriate execution resources. Returns a sender which +completes when the provided sender completes and sends values equivalent to +those of the provided sender.

+

If the returned sender is destroyed before execution::connect() is called, or +if execution::connect() is called but the returned operation-state is +destroyed before execution::start() is called, then a stop-request is sent to +the eagerly launched operation and the operation is detached and will run to +completion in the background. Its result will be discarded when it eventually +completes.

+

Note that the application will need to make sure that resources are kept alive +in the case that the operation detaches. e.g. by holding a std::shared_ptr to +those resources or otherwise having some out-of-band way to signal completion of +the operation so that resource release can be sequenced after the completion.

+

4.21. User-facing sender consumers

+

A sender consumer is an algorithm that takes one or more senders, which it +may execution::connect, as parameters, and does not return a sender.

+

4.21.1. execution::start_detached

+
void start_detached(
+    execution::sender auto sender
+);
+
+

Like ensure_started, but does not return a value; if the provided sender sends +an error instead of a value, std::terminate is called.

+

4.21.2. this_thread::sync_wait

+
auto sync_wait(
+    execution::sender auto sender
+) requires (always-sends-same-values(sender))
+    -> std::optional<std::tuple<values-sent-by(sender)>>;
+
+

this_thread::sync_wait is a sender consumer that submits the work described by +the provided sender for execution, similarly to ensure_started, except that it +blocks the current std::thread or thread of main until the work is +completed, and returns an optional tuple of values that were sent by the +provided sender on its completion of work. Where § 4.19.1 execution::schedule and § 4.19.2 execution::just are +meant to enter the domain of senders, sync_wait is meant to exit the domain of senders, retrieving the result of the task graph.

+

If the provided sender sends an error instead of values, sync_wait throws that +error as an exception, or rethrows the original exception if the error is of +type std::exception_ptr.

+

If the provided sender sends the "stopped" signal instead of values, sync_wait returns an empty optional.

+

For an explanation of the requires clause, see § 5.8 All senders are typed. That clause +also explains another sender consumer, built on top of sync_wait: sync_wait_with_variant.

+

Note: This function is specified inside std::this_thread, and not inside execution. This is because sync_wait has to block the current execution agent, but determining what the current execution agent is is not +reliable. Since the standard does not specify any functions on the current +execution agent other than those in std::this_thread, this is the flavor of +this function that is being proposed. If C++ ever obtains fibers, for instance, +we expect that a variant of this function called std::this_fiber::sync_wait would be provided. We also expect that runtimes with execution agents that use +different synchronization mechanisms than std::thread's will provide their own +flavors of sync_wait as well (assuming their execution agents have the means +to block in a non-deadlock manner).

+

4.22. execution::execute

+

In addition to the three categories of functions presented above, we also +propose to include a convenience function for fire-and-forget eager one-way +submission of an invocable to a scheduler, to fulfil the role of one-way +executors from P0443.

+
void execution::execute(
+    execution::schedule auto sched,
+    std::invocable auto fn
+);
+
+

Submits the provided function for execution on the provided scheduler, as-if by:

+
auto snd = execution::schedule(sched);
+auto work = execution::then(snd, fn);
+execution::start_detached(work);
+
+

5. Design - implementer side

+

5.1. Receivers serve as glue between senders

+

A receiver is a callback that supports more than one channel. In fact, it +supports three of them:

+
    +
  • +

    set_value, which is the moral equivalent of an operator() or a function +call, which signals successful completion of the operation its execution +depends on;

    +
  • +

    set_error, which signals that an error has happened during scheduling of the +current work, executing the current work, or at some earlier point in the +sender chain; and

    +
  • +

    set_stopped, which signals that the operation completed without succeeding +(set_value) and without failing (set_error). This result is often used +to indicate that the operation stopped early, typically because it was asked +to do so because the result is no longer needed.

    +
+

Once an async operation has been started exactly one of these functions must be +invoked on a receiver before it is destroyed.

+

While the receiver interface may look novel, it is in fact very similar to the +interface of std::promise, which provides the first two signals as set_value and set_exception, and it’s possible to emulate the third channel with +lifetime management of the promise.

+

Receivers are not a part of the end-user-facing API of this proposal; they are +necessary to allow unrelated senders communicate with each other, but the only +users who will interact with receivers directly are authors of senders.

+

Receivers are what is passed as the second argument to § 5.3 execution::connect.

+

5.2. Operation states represent work

+

An operation state is an object that represents work. Unlike senders, it is +not a chaining mechanism; instead, it is a concrete object that packages the +work described by a full sender chain, ready to be executed. An operation state +is neither movable nor copyable, and its interface consists of a single +algorithm: start, which serves as the submission point of the work represented +by a given operation state.

+

Operation states are not a part of the user-facing API of this proposal; they +are necessary for implementing sender consumers like execution::ensure_started and this_thread::sync_wait, and the knowledge of them is necessary to +implement senders, so the only users who will interact with operation states +directly are authors of senders and authors of sender algorithms.

+

The return value of § 5.3 execution::connect must satisfy the operation state +concept.

+

5.3. execution::connect

+

execution::connect is a customization point which connects senders with +receivers, resulting in an operation state that will ensure that if start is +called that one of the completion operations will be called on the receiver +passed to connect.

+
execution::sender auto snd = some input sender;
+execution::receiver auto rcv = some receiver;
+execution::operation_state auto state = execution::connect(snd, rcv);
+
+execution::start(state);
+// at this point, it is guaranteed that the work represented by state has been submitted
+// to an execution resource, and that execution resource will eventually call one of the
+// completion operations on rcv
+
+// operation states are not movable, and therefore this operation state object must be
+// kept alive until the operation finishes
+
+

5.4. Sender algorithms are customizable

+

Senders being able to advertise what their completion schedulers are +fulfills one of the promises of senders: that of being able to customize an +implementation of a sender algorithm based on what scheduler any work it depends +on will complete on.

+

The simple way to provide customizations for functions like then, that is for sender adaptors and sender consumers, is to follow the customization +scheme that has been adopted for C++20 ranges library; to do that, we would +define the expression execution::then(sender, invocable) to be equivalent to:

+
    +
  1. +

    sender.then(invocable), if that expression is well-formed; otherwise

    +
  2. +

    then(sender, invocable), performed in a context where this call always + performs ADL, if that expression is well-formed; otherwise

    +
  3. +

    a default implementation of then, which returns a sender adaptor, and + then define the exact semantics of said adaptor.

    +
+

However, this definition is problematic. Imagine another sender adaptor, bulk, +which is a structured abstraction for a loop over an index space. Its default +implementation is just a for loop. However, for accelerator runtimes like CUDA, +we would like sender algorithms like bulk to have specialized behavior, which +invokes a kernel of more than one thread (with its size defined by the call to bulk); therefore, we would like to customize bulk for CUDA senders to +achieve this. However, there’s no reason for CUDA kernels to necessarily +customize the then sender adaptor, as the generic implementation is perfectly +sufficient. This creates a problem, though; consider the following snippet:

+
execution::scheduler auto cuda_sch = cuda_scheduler{};
+
+execution::sender auto initial = execution::schedule(cuda_sch);
+// the type of initial is a type defined by the cuda_scheduler
+// let’s call it cuda::schedule_sender<>
+
+execution::sender auto next = execution::then(cuda_sch, []{ return 1; });
+// the type of next is a standard-library unspecified sender adaptor
+// that wraps the cuda sender
+// let’s call it execution::then_sender_adaptor<cuda::schedule_sender<>>
+
+execution::sender auto kernel_sender = execution::bulk(next, shape, [](int i){ ... });
+
+

How can we specialize the bulk sender adaptor for our wrapped schedule_sender? Well, here’s one possible approach, taking advantage of ADL +(and the fact that the definition of "associated namespace" also recursively +enumerates the associated namespaces of all template parameters of a type):

+
namespace cuda::for_adl_purposes {
+template<typename... SentValues>
+class schedule_sender {
+    execution::operation_state auto connect(execution::receiver auto rcv);
+    execution::scheduler auto get_completion_scheduler() const;
+};
+
+execution::sender auto bulk(
+    execution::sender auto && input,
+    execution::shape auto && shape,
+    invocable%lt;sender-values(input)> auto && fn)
+{
+    // return a cuda sender representing a bulk kernel launch
+}
+} // namespace cuda::for_adl_purposes
+
+

However, if the input sender is not just a then_sender_adaptor like in the +example above, but another sender that overrides bulk by itself, as a member +function, because its author believes they know an optimization for bulk - the +specialization above will no longer be selected, because a member function of +the first argument is a better match than the ADL-found overload.

+

This means that well-meant specialization of sender algorithms that are entirely +scheduler-agnostic can have negative consequences. The scheduler-specific +specialization - which is essential for good performance on platforms providing +specialized ways to launch certain sender algorithms - would not be selected in +such cases. But it’s really the scheduler that should control the behavior of +sender algorithms when a non-default implementation exists, not the sender. +Senders merely describe work; schedulers, however, are the handle to the runtime +that will eventually execute said work, and should thus have the final say in how the work is going to be executed.

+

Therefore, we are proposing the following customization scheme: the expression execution::<sender-algorithm>(sender, args...), for any given sender algorithm +that accepts a sender as its first argument, should do the following:

+
    +
  1. +

    Create a sender that implements the default implementation of the sender + algorithm. That sender is tuple-like; it can be destructured into its + constituent parts: algorithm tag, data, and child sender(s).

    +
  2. +

    We query the child sender for its domain. A domain is a tag type + associated with the scheduler that the child sender will complete on. + If there are multiple child senders, we query all of them for their + domains and require that they all be the same.

    +
  3. +

    We use the domain to dispatch to a transform_sender customization, which + accepts the sender and optionally performs a domain-specific + transformation on it. This customization is expected to return a new + sender, which will be returned from <sender-algorithm> in place of the + original sender.

    +
+

5.5. Sender adaptors are lazy

+

Contrary to early revisions of this paper, we propose to make all sender +adaptors perform strictly lazy submission, unless specified otherwise (the one +notable exception in this paper is § 4.20.12 execution::ensure_started, +whose sole purpose is to start an input sender).

+

Strictly lazy submission means that there is a guarantee +that no work is submitted to an execution resource before a receiver is +connected to a sender, and execution::start is called on the resulting +operation state.

+

5.6. Lazy senders provide optimization opportunities

+

Because lazy senders fundamentally describe work, instead of describing or +representing the submission of said work to an execution resource, and thanks to +the flexibility of the customization of most sender algorithms, they provide an +opportunity for fusing multiple algorithms in a sender chain together, into a +single function that can later be submitted for execution by an execution +resource. There are two ways this can happen.

+

The first (and most common) way for such optimizations to happen is thanks to +the structure of the implementation: because all the work is done within +callbacks invoked on the completion of an earlier sender, recursively up to the +original source of computation, the compiler is able to see a chain of work +described using senders as a tree of tail calls, allowing for inlining and +removal of most of the sender machinery. In fact, when work is not submitted to +execution resources outside of the current thread of execution, compilers are +capable of removing the senders abstraction entirely, while still allowing for +composition of functions across different parts of a program.

+

The second way for this to occur is when a sender algorithm is specialized for a +specific set of arguments. For instance, we expect that, for senders which are +known to have been started already, § 4.20.12 execution::ensure_started will be an identity transformation, because the sender algorithm will be +specialized for such senders. Similarly, an implementation could recognize two +subsequent § 4.20.9 execution::bulks of compatible shapes, and merge them +together into a single submission of a GPU kernel.

+

5.7. Execution resource transitions are two-step

+

Because execution::transfer takes a sender as its first argument, it is not +actually directly customizable by the target scheduler. This is by design: the +target scheduler may not know how to transition from a scheduler such as +a CUDA scheduler; transitioning away from a GPU in an efficient manner requires +making runtime calls that are specific to the GPU in question, and the same is +usually true for other kinds of accelerators too (or for scheduler running on +remote systems). To avoid this problem, specialized schedulers like the ones +mentioned here can still hook into the transition mechanism, and inject a sender +which will perform a transition to the regular CPU execution resource, so that +any sender can be attached to it.

+

This, however, is a problem: because customization of sender algorithms must be +controlled by the scheduler they will run on (see § 5.4 Sender algorithms are customizable), +the type of the sender returned from transfer must be controllable by the +target scheduler. Besides, the target scheduler may itself represent a +specialized execution resource, which requires additional work to be performed +to transition to it. GPUs and remote node schedulers are once again good +examples of such schedulers: executing code on their execution resources +requires making runtime API calls for work submission, and quite possibly for +the data movement of the values being sent by the input sender passed into transfer.

+

To allow for such customization from both ends, we propose the inclusion of a +secondary transitioning sender adaptor, called schedule_from. This adaptor is +a form of schedule, but takes an additional, second argument: the input +sender. This adaptor is not meant to be invoked manually by the end users; they +are always supposed to invoke transfer, to ensure that both schedulers have a +say in how the transitions are made. Any scheduler that specializes transfer(snd, sch) shall ensure that the return value of their customization +is equivalent to schedule_from(sch, snd2), where snd2 is a successor of snd that sends values equivalent to those sent by snd.

+

The default implementation of transfer(snd, sched) is schedule_from(sched, snd).

+

5.8. All senders are typed

+

All senders must advertise the types they will send when they complete. There +are many sender adaptors that need this information. Even just transitioning +from one execution context to another requires temporarily storing the async +result data so it can be propagated in the new execution context. Doing that +efficiently requires knowing the type of the data.

+

The mechanism a sender uses to advertise its completions is the get_completion_signatures customization point, which takes an environment and +must return a specialization of the execution::completion_signatures class +template. The template parameters of execution::completion_signatures is a +list of function types that represent the completion operations of the sender. +for example, the type execution::set_value_t(size_t, const char*) indicates +that the sender can complete successfully by passing a size_t and a const char* to the receiver’s set_value function.

+

This proposal includes utilities for parsing and manipulating the list of a +sender’s completion signatures. For instance, values_of_t is a template alias +for accessing a sender’s value completions. It takes a sender, an environment, +and two variadic template template parameters: a tuple-like template and a +variant-like template. You can get the value completions of S and Env with value_types_of_t<S, Env, tuple-like, variant-like>. For example, for a sender that can complete +successfully with either Ts... or Us..., value_types_of_t<S, Env, std::tuple, std::variant> would name the type std::variant<std::tuple<Ts...>, std::tuple<Us...>>.

+

5.9. Customization points

+

Earlier versions of this paper used a dispatching technique known as tag_invoke (see tag_invoke: A general pattern for supporting customisable functions) to allow for customization of basis operations +and sender algorithms. This technique used private friend functions named +"tag_invoke" that are found by argument-dependent look-up. The tag_invoke overloads are distinguished from each other by their first argument, which is +the type of the customization point object being customized. For instance, to +customize the execution::set_value operation, a receiver type might do the +following:

+
struct my_receiver {
+  friend void tag_invoke(execution::set_value_t, my_receiver&& self, int value) noexcept {
+    std::cout << "received value: " << value;
+  }
+  //...
+};
+
+

The tag_invoke technique, although it had its strengths, has been replaced +with a new (or rather, a very old) technique that uses explicit concept opt-ins +and named member functions. For instance, the execution::set_value operation +is now customized by defining a member function named set_value in the +receiver type. This technique is more explicit and easier to understand than tag_invoke. This is what a receiver author would do to customize execution::set_value now:

+
struct my_receiver {
+  using receiver_concept = execution::receiver_t;
+
+  void set_value(int value) && noexcept {
+    std::cout << "received value: " << value;
+  }
+  //...
+};
+
+

The only exception to this is the customization of queries. There is a need to +build queryable adaptors that can forward and open and unknowable set of queries +to some wrapped object. This is done by defining a member function named query in the adaptor type that takes the query CPO object as its first +(and usually only) argument. A queryable adaptor might look like this:

+
template <class Query, class Queryable, class... Args>
+concept query_for =
+  execution::queryable<Queryable> &&
+  requires (const Queryable& o, Args&&... args) {
+    o.query(Query(), (Args&&) args...);
+  };
+
+template<class Allocator = std::allocator<>,
+         execution::queryable Base = execution::empty_env>
+struct with_allocator {
+  Allocator alloc{};
+  Base base{};
+
+  // Forward unknown queries to the wrapped object:
+  template<query_for<Base> Query>
+  decltype(auto) query(Query q) const {
+    return base.query(q);
+  }
+
+  // Specialize the query for the allocator:
+  Allocator query(execution::get_allocator_t) const {
+    return alloc;
+  }
+};
+
+

Customization of sender algorithms such as execution::then and execution::bulk are handled differently because they must dispatch based on +where the sender is executing. See the section on § 5.4 Sender algorithms are customizable for +more information.

+

6. Specification

+

Much of this wording follows the wording of A Unified Executors Proposal for C++.

+

§ 22 General utilities library [utilities] is meant to be a diff relative to the wording of the [utilities] clause of Working Draft, Standard for Programming Language C++.

+

§ 33 Concurrency support library [thread] is meant to be a diff relative to the wording of the [thread] clause of Working Draft, Standard for Programming Language C++. This diff applies changes from Composable cancellation for sender-based async operations.

+

§ 34 Execution control library [exec] is meant to be added as a new library clause to the working +draft of C++.

+
+

7.

+

8.

+

9.

+

10.

+

11.

+

12.

+

13.

+
+
+

14. Exception handling [except]

+ +

14.6. Special functions [except.special]

+ +

14.6.2. The std::terminate function [except.terminate]

+

At the end of the bulleted list in the Note in paragraph 1, add +a new bullet as follows:

+
+
    +
  • +

    when a call to a wait(), wait_until(), or wait_for() function on a +condition variable (33.7.4, 33.7.5) fails to meet a postcondition.

    +
+
+
    +
  • +

    when a callback invocation exits via an exception when requesting stop on a std::stop_source or a std::inplace_stop_source ([stopsource.mem], +[stopsource.inplace.mem]), or in the constructor of std::stop_callback or std::inplace_stop_callback ([stopcallback.cons], +[stopcallback.inplace.cons]) when a callback invocation exits via an +exception.

    +
+
+
+
+ +
+

16. Library introduction [library]

+

At the end of [expos.only.entity], add the following:

+
    +
  1. +

    The following are defined for exposition only to aid in the specification of +the library:

    +
    namespace std {
    +  // ...as before...
    +}
    +
    +
+
+
    +
  1. +

    An object dst is said to be decay-copied from a +subexpression src if the type of dst is decay_t<decltype((src))>, +and dst is copy-initialized from src.

    +
+
+
+ +
+

22. General utilities library [utilities]

+ +

22.10. Function objects [function.objects]

+ +

22.10.2. Header <functional> synopsis [functional.syn]

+

At the end of this subclause, insert the following +declarations into the synopsis within namespace std:

+
namespace std {
+  // ...as before...
+
+  namespace ranges {
+    // 22.10.9, concept-constrained comparisons
+    struct equal_to;                                    // freestanding
+    struct not_equal_to;                                // freestanding
+    struct greater;                                     // freestanding
+    struct less;                                        // freestanding
+    struct greater_equal;                               // freestanding
+    struct less_equal;                                  // freestanding
+  }
+
+
template<class Fn, class... Args> + concept callable = // exposition only + requires (Fn&& fn, Args&&... args) { + std::forward<Fn>(fn)(std::forward<Args>(args)...); + }; + template<class Fn, class... Args> + concept nothrow-callable = // exposition only + callable<Fn, Args...> && + requires (Fn&& fn, Args&&... args) { + { std::forward<Fn>(fn)(std::forward<Args>(args)...) } noexcept; + }; + // exposition only: + template<class Fn, class... Args> + using call-result-t = decltype(declval<Fn>()(declval<Args>()...)); + + template<const auto& Tag> + using decayed-typeof = decltype(auto(Tag)); // exposition only
+} +
+
+ +
+

33. Concurrency support library [thread]

+ +

33.3. Stop tokens [thread.stoptoken]

+

33.3.1. Introduction [thread.stoptoken.intro]

+
    +
  1. +

    Subclause [thread.stoptoken] describes components that can be used to +asynchronously request that an operation stops execution in a timely manner, +typically because the result is no longer required. Such a request is called +a stop request.

    +
  2. + stop_source, stop_token, and stop_callback implement + stoppable-source, stoppable_token, and stoppable-callback-for are concepts that specify the required +syntax and + semantics of shared + ownership + access + of a stop state. + Any stop_source, stop_token, or stop_callback object that shares ownership of the same +stop state is an associated stop_source, stop_token, or stop_callback, respectively. + Any object modeling stoppable-source, stoppable_token, or stoppable-callback-for that refers to the same stop state is an associated stoppable-source, stoppable_token, or stoppable-callback-for, +respectively. + The last remaining owner of the stop state +automatically releases the resources associated with the stop state. +
  3. +

    + A stoppable_token can be passed to an operation + which + that + can either +

    +
    +
      +
    • +

      actively poll the token to check if there has been a stop request, or

      +
    • +

      + register a callback + using the stop_callback class +template which + that + will be called in the event that a +stop request is made. +

      +
    +
    +

    +

    + A stop request made via + a stop_source + an object that models stoppable-source + will be visible to all associated stoppable_token and + stop_source + stoppable-source + objects. Once a stop request has been +made it cannot be withdrawn (a subsequent stop request has no effect). +

    +
  4. +

    + Callbacks registered via + a stop_callback object + an object +that models stoppable-callback-for + are called when a stop +request is first made by any associated + stop_source + stoppable-source + object. +

    +
+

The following paragraph is moved to the specification of +the new stoppable-source concept.

+
+
    +
  1. +

    Calls to the functions request_stop, stop_requested, and stop_possible do not introduce data races. A call to request_stop that returns true synchronizes with a call to stop_requested on an associated stop_token or stop_source object that returns true. Registration of a callback +synchronizes with the invocation of that callback.

    +
+
+
+
    +
  1. +

    The types stop_source and stop_token and the class template stop_callback implement the semantics of shared ownership of a stop state. +The last remaining owner of the stop state automatically releases the +resources associated with the stop state.

    +
  2. +

    The types inplace_stop_source and inplace_stop_token and the class +template inplace_stop_callback do no dynamic memory allocation or reference +counting of the stop state. They are for use when the lifetimes of the tokens +and the callbacks are known to nest within the lifetime of the source.

    +
+
+

33.3.2. Header <stop_token> synopsis [thread.stoptoken.syn]

+

In this subclause, insert the following +declarations into the <stop_token> synopsis:

+
namespace std {
+
// [stoptoken.concepts], stop token concepts + template<class Callback, class Token, class Initializer = Callback> + concept stoppable-callback-for = see below; // exposition only + + template<class Token> + concept stoppable_token = see below; + + template<class Token> + concept unstoppable_token = see below; + + template<class Source> + concept stoppable-source = see below; // exposition only
+ // 33.3.3, class stop_token + class stop_token; + + // 33.3.4, class stop_source + class stop_source; + + // no-shared-stop-state indicator + struct nostopstate_t { + explicit nostopstate_t() = default; + }; + inline constexpr nostopstate_t nostopstate{}; + + // 33.3.5, class template stop_callback + template<class Callback> + class stop_callback; + +
// [stoptoken.never], class never_stop_token + class never_stop_token; + + // [stoptoken.inplace], class inplace_stop_token + class inplace_stop_token; + + // [stopsource.inplace], class inplace_stop_source + class inplace_stop_source; + + // [stopcallback.inplace], class template inplace_stop_callback + template<class Callback> + class inplace_stop_callback; + + template<class T, class Callback> + using stop_callback_for_t = T::template callback_type<Callback>;
+} +
+
+

Insert the following subclause as a new subclause between +Header <stop_token> synopsis [thread.stoptoken.syn] and Class stop_token [stoptoken].

+
+
+

33.3.3. Stop token concepts [stoptoken.concepts]

+
    +
  1. +

    For a stop token type Token and a type Callback that is callable with no +arguments, if the type stop_callback_for_t<Token, Callback> is valid, it +denotes the type of a stop callback to use to register a callback to be +executed if a stop request is ever made on the stoppable_token's +associated stop source. The exposition-only stoppable-callback-for concept checks for a callback compatible with a given stop token type.

    +
    template<class Callback, class Token, class Initializer = Callback>
    +  concept stoppable-callback-for = // exposition only
    +    invocable<Callback> &&
    +    constructible_from<Callback, Initializer> &&
    +    requires { typename stop_callback_for_t<Token, Callback>; } &&
    +    constructible_from<stop_callback_for_t<Token, Callback>, const Token&, Initializer>;
    +
    +
  2. +

    Let t and u be distinct, valid objects of type Token that reference the +same logical stop state; let init be an object of type Initializer; and let CB denote the type stop_callback_for_t<Token, Callback>.

    +
  3. +

    The concept stoppable-callback-for<Callback, Token, Initializer> is modeled only if:

    +
      +
    1. +

      The following concepts are modeled:

      +
        +
      • +

        constructible_from<CB, Token, Initializer>

        +
      • +

        constructible_from<CB, Token&, Initializer>

        +
      • +

        constructible_from<CB, const Token, Initializer>

        +
      +
    2. +

      An object of type CB has an associated callback +function of type Callback. Let cb be an object of type CB and let callback denote cb's associated callback function. +Direct-non-list-initializing cb from arguments t and init shall +execute a stoppable callback registration as +follows:

      +
        +
      1. +

        If t.stop_possible() is true:

        +
          +
        1. +

          callback shall be direct-initialized with init.

          +
        2. +

          Construction of cb shall only throw exceptions thrown by the +initialization of callback from init.

          +
        3. +

          The callback invocation std::forward<Callback>(callback)() shall +be registered with t's associated stop state as follows:

          +
            +
          1. +

            If t.stop_requested() evaluates to false at the time of +registration, the callback invocation is added to the stop +state’s list of callbacks such that std::forward<Callback>(callback)() is +evaluated if a stop request is made on the stop state.

            +
          2. +

            Otherwise, std::forward<Callback>(callback)() shall be immediately evaluated on the thread executing cb's constructor, and the callback invocation shall not be +added to the list of callback invocations.

            +
          +
        4. +

          If the callback invocation was added to stop state’s list of +callbacks, cb shall be associated with the stop state.

          +
        +
      2. +

        If t.stop_possible() is false, there is no +requirement that the initialization of cb causes the +initialization of callback.

        +
      +
    3. +

      An evaluation of u.stop_requested() that strongly happens after +([intro.races]/10) the beginning of the invocation of callback shall return true.

      +
    4. +

      Destruction of cb shall execute a stoppable callback +deregistration as follows:

      +
        +
      1. +

        If the constructor of cb did not register a callback invocation +with t's stop state, then the stoppable callback +deregistration shall have no effect.

        +
      2. +

        Otherwise, the invocation of callback shall be removed from +the associated stop state.

        +
      3. +

        If callback is currently being invoked on another thread +then the stoppable callback deregistration shall block +([defns.block]) until the invocation of callback returns +such that the return from the invocation of callback strongly happens before ([intro.races]) the destruction of callback.

        +
      4. +

        If callback is executing on the current thread, then the +destructor shall not block waiting for the return from the +invocation of callback.

        +
      5. +

        A stoppable callback deregistration shall not block on the completion +of the invocation of some other callback registered with the same +logical stop state.

        +
      6. +

        As a final step, the stoppable callback deregistration shall destroy +the callback function.

        +
      +
    +
  4. +

    The stoppable_token concept checks for the basic interface of a stop token +that is copyable and allows polling to see if stop has been requested and +also whether a stop request is possible. The unstoppable_token concept +checks for a stop token type that does not allow stopping.

    +
    template<template<class> class>
    +  struct check-type-alias-exists; // exposition-only
    +
    +template<class Token>
    +  concept stoppable_token =
    +    requires (const Token tok) {
    +      typename check-type-alias-exists<Token::template callback_type>;
    +      { tok.stop_requested() } noexcept -> same_as<bool>;
    +      { tok.stop_possible() } noexcept -> same_as<bool>;
    +      { Token(tok) } noexcept; // see implicit expression variations
    +                               // ([concepts.equality])
    +    } &&
    +    copyable<Token> &&
    +    equality_comparable<Token> &&
    +    swappable;
    +
    +template<class Token>
    +  concept unstoppable_token =
    +    stoppable_token<Token> &&
    +    requires (const Token tok) {
    +      requires bool_constant<(!tok.stop_possible())>::value;
    +    };
    +
    +
  5. +

    The type Token models stoppable_token only if:

    +
      +
    1. +

      If an evaluation, E, of t.stop_possible() evaluates to false, then +evaluations of u.stop_possible() and u.stop_requested() that happen +after E shall evaluate to false.

      +
    2. +

      If an evaluation, E, of t.stop_requested() evaluates to true, then +evaluations of u.stop_possible() and u.stop_requested() that happens +after E shall evaluate to true.

      +
    3. +

      For any types Callback and Initializer, if stoppable-callback-for<Callback, Token, Initializer> is satisfied, then stoppable-callback-for<Callback, Token, Initializer> shall be modeled.

      +
    4. +

      An object that models stoppable_token has at most one associated +logical stop state. A stoppable_token object with no associated stop +state is said to be disengaged. For a disengaged stoppable_token object, stop_possible and stop_requested shall +return false. If t and u reference the same stop state, or if both t and u are disengaged, t == u shall be true; otherwise, it +shall be false.

      +
    +
  6. +

    A model of the exposition-only stoppable-source concept can be +queried whether stop has been requested (stop_requested) and whether stop +is possible (stop_possible). It is a factory for associated stop tokens +(get_token) and can be explicitly placed into the "stop requested" state +(request_stop). It maintains a list of registered stop callback +invocations that it executes when a stop request is first made.

    +
    template<class Source>
    +  concept stoppable-source = // exposition only
    +    requires (Source& src, const Source csrc) { // see implicit expression variations
    +                                                // ([concepts.equality])
    +      { csrc.get_token() } -> stoppable_token;
    +      { csrc.stop_possible() } noexcept -> same_as<bool>;
    +      { csrc.stop_requested() } noexcept -> same_as<bool>;
    +      { src.request_stop() } -> same_as<bool>;
    +    };
    +
    +
      +
    1. +

      A stoppable-source object has at most one associated logical +stop state. A stoppable-source object with no associated stop +state is said to be disengaged. For a disengaged stoppable-source object, stop_possible and stop_requested shall return false.

      +
    2. +

      A disengaged stoppable-source object shall return a disengaged +stop token from get_token(). Otherwise, get_token() shall return a +stop token that is associated with the stop state of the source.

      +
    +

    The following paragraph is moved from the introduction, +with minor modifications (underlined in green).

    +
      +
    1. +

      + Calls to the + member + functions request_stop, stop_requested, and stop_possible + and similarly named member +functions on associated stoppable_token objects + do not introduce +data races. A call to request_stop that returns true synchronizes +with a call to stop_requested on an associated stoppable_token or + stop_source + stoppable-source + object that returns true. Registration +of a callback synchronizes with the invocation of that callback. +

      +
    +

    The following paragraph is taken from § 33.3.5.3 Member functions [stopsource.mem] and modified.

    +
      +
    1. +

      If the stoppable-source is disengaged, request_stop shall have +no effect and return false. Otherwise, it shall execute a stop request operation on the associated stop state. A +stop request operation determines whether the stop state has received a +stop request, and if not, makes a stop request. The determination and +making of the stop request shall happen atomically, as-if by a +read-modify-write operation ([intro.races]). If the request was made, +the stop state’s registered callback invocations shall be synchronously +executed. If an invocation of a callback exits via an exception then terminate shall be invoked ([except.terminate]). No constraint is placed on the order in which the +callback invocations are executed. request_stop shall return true if a stop request was made, and false otherwise. After a call +to request_stop either stop_possible() shall be false or stop_requested() shall be true.

      +

      A stop request includes notifying all condition +variables of type condition_variable_any temporarily registered during an +interruptible wait ([thread.condvarany.intwait]).

      +
    +
+
+
+

Modify subclause [stoptoken] as follows:

+
+

33.3.4. Class stop_token [stoptoken]

+
33.3.4.1. General [stoptoken.general]
+
    +
  1. + The class stop_token provides an interface for querying whether a stop +request has been made (stop_requested) or can ever be made (stop_possible) +using an associated stop_source object ([stopsource]). A stop_token can also be +passed to a stop_callback ([stopcallback]) constructor to register a callback to be +called when a stop request has been made from an associated stop_source. + The class stop_token models the concept stoppable_token. It shares ownership of its stop state, if any, with its +associated stop_source object ([stopsource]) and any stop_token objects +to which it compares equal. +
+
namespace std {
+  class stop_token {
+  public:
+
template<class T> + using callback_type = stop_callback<T>;
+ // [stoptoken.cons], constructors, copy, and assignment + stop_token() noexcept = default; + +
stop_token(const stop_token&) noexcept; + stop_token(stop_token&&) noexcept; + stop_token& operator=(const stop_token&) noexcept; + stop_token& operator=(stop_token&&) noexcept; + ~stop_token();
+ + // [stoptoken.mem], Member functions + void swap(stop_token&) noexcept; + + // [stoptoken.mem], stop handling + [[nodiscard]] bool stop_requested() const noexcept; + [[nodiscard]] bool stop_possible() const noexcept; + + bool operator==(const stop_token& rhs) const noexcept = default; + [[nodiscard]] friend bool operator==(const stop_token& lhs, const stop_token& rhs) noexcept; + friend void swap(stop_token& lhs, stop_token& rhs) noexcept; + private: + shared_ptr<unspecified> stop-state{}; // exposition only + }; +} +
+
+
    +
  1. +

    stop-state refers to the stop_token's associated stop state. A stop_token object is disengaged when stop-state is null.

    +
+
+

+
+
+
33.3.4.2. Constructors, copy, and assignment [stoptoken.cons]
+
stop_token() noexcept;
+
+
    +
  1. +

    + Postconditions: + stop_possible() is false and stop_requested() is false. + Because the created stop_token object can never receive a stop request, no resources are allocated for a +stop state. +

    +
+
stop_token(const stop_token& rhs) noexcept;
+
+
    +
  1. +

    Postconditions: *this == rhs is true. *this and rhs share the ownership of the same stop state, if any.

    +
+
stop_token(stop_token&& rhs) noexcept;
+
+
    +
  1. +

    Postconditions: *this contains the value of rhs prior to the start of +construction and rhs.stop_possible() is false.

    +
+
~stop_token();
+
+
    +
  1. +

    Effects: Releases ownership of the stop state, if any.

    +
+
stop_token& operator=(const stop_token& rhs) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: stop_token(rhs).swap(*this).

    +
  2. +

    Returns: *this.

    +
+
stop_token& operator=(stop_token&& rhs) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: stop_token(std::move(rhs)).swap(*this).

    +
  2. +

    Returns: *this.

    +
+
+

Move swap into [stoptoken.mem]:

+
33.3.4.3. Member functions [stoptoken.mem]
+
void swap(stop_token& rhs) noexcept;
+
+
    +
  1. +

    + Effects: + Exchanges the values of *this and rhs. + Equivalent to: std::swap(stop-state, rhs.stop-state). +

    +
+
[[nodiscard]] bool stop_requested() const noexcept;
+
+
    +
  1. +

    + Returns: true if + *this has ownership +of + stop-state refers to + a stop state that has +received a stop request; otherwise, false. +

    +
+
[[nodiscard]] bool stop_possible() const noexcept;
+
+
    +
  1. +

    Returns: false if:

    +
    +
      +
    • +

      + *this + does not have ownership of a stop state + is disengaged + , or +

      +
    • +

      a stop request was not made and there are no associated stop_source objects; otherwise, true.

      +
    +
    +
+

The following are covered by the equality_comparable and swappable concepts.

+
+
33.3.4.4. Non-member functions [stoptoken.nonmembers]
+
[[nodiscard]] bool operator==(const stop_token& lhs, const stop_token& rhs) noexcept;
+
+
    +
  1. +

    Returns: true if lhs and rhs have ownership of the same stop state or +if both lhs and rhs do not have ownership of a stop state; otherwise false.

    +
+
friend void swap(stop_token& x, stop_token& y) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: x.swap(y).

    +
+
+
+

33.3.5. Class stop_source [stopsource]

+
33.3.5.1. General [stopsource.general]
+
    +
  1. +

    + The class stop_source + implements the semantics of making a stop +request. A stop request made on a stop_source object is visible to all +associated stop_source and stop_token ([thread.stoptoken]) objects. Once +a stop request has been made it cannot be withdrawn (a subsequent stop +request has no effect) + models stoppable-source + . +

    +
+
namespace std {
+  The following definitions are already specified in the <stop_token> synopsis:
+
// no-shared-stop-state indicator + struct nostopstate_t { + explicit nostopstate_t() = default; + }; + inline constexpr nostopstate_t nostopstate{};
+ + class stop_source { + public: + // 33.3.4.2, constructors, copy, and assignment + stop_source(); + explicit stop_source(nostopstate_t) noexcept; {} + +
stop_source(const stop_source&) noexcept; + stop_source(stop_source&&) noexcept; + stop_source& operator=(const stop_source&) noexcept; + stop_source& operator=(stop_source&&) noexcept; + ~stop_source();
+ + // [stopsource.mem], Member functions + void swap(stop_source&) noexcept; + + // 33.3.4.3, stop handling + [[nodiscard]] stop_token get_token() const noexcept; + [[nodiscard]] bool stop_possible() const noexcept; + [[nodiscard]] bool stop_requested() const noexcept; + bool request_stop() noexcept; + + bool operator==(const stop_source& rhs) const noexcept = default; +
[[nodiscard]] friend bool + operator==(const stop_source& lhs, const stop_source& rhs) noexcept; + friend void swap(stop_source& lhs, stop_source& rhs) noexcept;
+ private: + shared_ptr<unspecified> stop-state{}; // exposition only + }; +} +
+
+
    +
  1. +

    stop-state refers to the stop_source's associated stop state. A stop_source object is disengaged when stop-state is null.

    +
  2. +

    stop_source models copyable, equality_comparable, and swappable.

    +
+
+
33.3.5.2. Constructors, copy, and assignment [stopsource.cons]
+
stop_source();
+
+
    +
  1. +

    + Effects: Initialises + *this to have ownership +of + stop-state with a pointer to + a new stop state. +

    +
  2. +

    Postconditions: stop_possible() is true and stop_requested() is false.

    +
  3. +

    Throws: bad_alloc if memory cannot be allocated for the stop state.

    +
+
+
explicit stop_source(nostopstate_t) noexcept;
+
+
    +
  1. +

    Postconditions: stop_possible() is false and stop_requested() is false. No resources are allocated for the state.

    +
+
stop_source(const stop_source& rhs) noexcept;
+
+
    +
  1. +

    Postconditions: *this == rhs is true. *this and rhs share the ownership of the same stop state, if any.

    +
+
stop_source(stop_source&& rhs) noexcept;
+
+
    +
  1. +

    Postconditions: *this contains the value of rhs prior to the start of construction and rhs.stop_possible() is false.

    +
+
~stop_source();
+
+
    +
  1. +

    Effects: Releases ownership of the stop state, if any.

    +
+
stop_source& operator=(const stop_source& rhs) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: stop_source(rhs).swap(*this).

    +
  2. +

    Returns: *this.

    +
+
stop_source& operator=(stop_source&& rhs) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: stop_source(std::move(rhs)).swap(*this).

    +
  2. +

    Returns: *this.

    +
+
+

Move swap into [stopsource.mem]:

+
33.3.5.3. Member functions [stopsource.mem]
+
void swap(stop_source& rhs) noexcept;
+
+
    +
  1. +

    + Effects: + Exchanges the values of *this and rhs + Equivalent to: std::swap(stop-state, rhs.stop-state) + . +

    +
+
[[nodiscard]] stop_token get_token() const noexcept;
+
+
    +
  1. +

    + Returns: stop_token() if stop_possible() is false; otherwise a new +associated stop_token object + ; i.e., its stop-state pointer +is equal to the stop-state pointer of *this + . +

    +
+
[[nodiscard]] bool stop_possible() const noexcept;
+
+
    +
  1. +

    + Returns: + true if *this has ownership of a stop state; otherwise, false + stop-state != nullptr + . +

    +
+
[[nodiscard]] bool stop_requested() const noexcept;
+
+
    +
  1. +

    + Returns: true if + *this has ownership +of + stop-state refers to + a stop state that has +received a stop request; otherwise, false. +

    +
+
bool request_stop() noexcept;
+
+
+
    +
  1. +

    Effects: Executes a stop request operation ([stoptoken.concepts]) on the +associated stop state, if any.

    +
+
+
+
    +
  1. +

    Effects: If *this does not have ownership of a stop state, returns false. Otherwise, atomically determines whether the owned stop state has +received a stop request, and if not, makes a stop request. The determination +and making of the stop request are an atomic read-modify-write operation +([intro.races]). If the request was made, the callbacks registered by +associated stop_callback objects are synchronously called. If an +invocation of a callback exits via an exception then terminate is invoked +([except.terminate]).

    +

    A stop request includes notifying all condition +variables of type condition_variable_any temporarily registered during an +interruptible wait ([thread.condvarany.intwait]).

    +
  2. +

    Postconditions: stop_possible() is false or stop_requested() is true.

    +
  3. +

    Returns: true if this call made a stop request; otherwise false.

    +
+
+
+
33.3.5.4. Non-member functions [stopsource.nonmembers]
+
[[nodiscard]] friend bool
+  operator==(const stop_source& lhs, const stop_source& rhs) noexcept;
+
+
    +
  1. +

    Returns: true if lhs and rhs have ownership of the same stop state or if +both lhs and rhs do not have ownership of a stop state; otherwise false.

    +
+
friend void swap(stop_source& x, stop_source& y) noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: x.swap(y).

    +
+
+
+
+

33.3.6. Class template stop_callback [stopcallback]

+
33.3.6.1. General [stopcallback.general]
+
    +
  1. +
+
namespace std {
+  template<class Callback>
+  class stop_callback {
+  public:
+    using callback_type = Callback;
+
+    // 33.3.5.2, constructors and destructor
+    template<class C>
+      explicit stop_callback(const stop_token& st, C&& cb)
+        noexcept(is_nothrow_constructible_v<Callback, C>);
+    template<class C>
+      explicit stop_callback(stop_token&& st, C&& cb)
+        noexcept(is_nothrow_constructible_v<Callback, C>);
+    ~stop_callback();
+
+    stop_callback(const stop_callback&) = delete;
+    stop_callback(stop_callback&&) = delete;
+    stop_callback& operator=(const stop_callback&) = delete;
+    stop_callback& operator=(stop_callback&&) = delete;
+
+  private:
+    Callback callback; // exposition only
+  };
+
+  template<class Callback>
+    stop_callback(stop_token, Callback) -> stop_callback<Callback>;
+}
+
+
    +
  1. +

    Mandates: stop_callback is instantiated with an argument for the template +parameter Callback that satisfies both invocable and destructible.

    +
+
+
    +
  1. +

    Preconditions: stop_callback is instantiated with an argument for the +template parameter Callback that models both invocable and destructible.

    +
+
+
+
    +
  1. +

    Remarks: For a type C, if stoppable-callback-for<Callback, stop_token, C> is +satisfied, then stoppable-callback-for<Callback, stop_token, C> is modeled. The exposition-only callback member is the +associated callback function ([stoptoken.concepts]) of stop_callback<Callback> objects.

    +
+
+
33.3.6.2. Constructors and destructor [stopcallback.cons]
+
template<class C>
+explicit stop_callback(const stop_token& st, C&& cb)
+  noexcept(is_nothrow_constructible_v<Callback, C>);
+template<class C>
+explicit stop_callback(stop_token&& st, C&& cb)
+  noexcept(is_nothrow_constructible_v<Callback, C>);
+
+
    +
  1. +

    Constraints: Callback and C satisfy constructible_from<Callback, C>.

    +
+
+
    +
  1. +

    Preconditions: Callback and C model constructible_from<Callback, C>.

    +
+
+
    +
  1. +

    + Effects: Initializes callback with std::forward<C>(cb) + and +executes a stoppable callback registration ([stoptoken.concepts]) + . + If st.stop_requested() is true, then std::forward<Callback>(callback)() is evaluated in the current thread before the constructor returns. +Otherwise, if st has ownership of a stop state, acquires shared ownership +of that stop state and registers the callback with that stop state such that std::forward<Callback>(callback)() is evaluated by the first call to request_stop() on an associated stop_source. + If a callback +is registered with st's shared stop state, then *this acquires shared +ownership of that stop state. +

    +
+
+
    +
  1. +

    Throws: Any exception thrown by the initialization of callback.

    +
  2. +

    Remarks: If evaluating std::forward<Callback>(callback)() exits via an +exception, then terminate is invoked ([except.terminate]).

    +
+
+
~stop_callback();
+
+
    +
  1. +

    + Effects: + Unregisters the callback from the owned stop state, if any. +The destructor does not block waiting for the execution of another callback +registered by an associated stop_callback. If callback is concurrently +executing on another thread, then the return from the invocation of callback strongly happens before ([intro.races]) callback is destroyed. +If callback is executing on the current thread, then the destructor does +not block ([defns.block]) waiting for the return from the invocation of callback. Releases + Executes a stoppable callback deregistration +([stoptoken.concepts]), and releases + ownership of the stop state, if +any. +

    +
+
+

Insert a new subclause, Class never_stop_token [stoptoken.never], after subclause Class template stop_callback [stopcallback], as a new subclause of Stop tokens [thread.stoptoken].

+
+
+

33.3.7. Class never_stop_token [stoptoken.never]

+
33.3.7.1. General [stoptoken.never.general]
+
    +
  1. +

    The class never_stop_token models the unstoppable_token concept. It +provides a stop token interface, but also provides static information that a +stop is never possible nor requested.

    +
    namespace std {
    +  class never_stop_token {
    +    struct callback { // exposition only
    +      explicit callback(never_stop_token, auto&&) noexcept {}
    +    };
    +  public:
    +    template<class>
    +      using callback_type = callback;
    +
    +    static constexpr bool stop_requested() noexcept { return false; }
    +    static constexpr bool stop_possible() noexcept { return false; }
    +
    +    bool operator==(const never_stop_token&) const noexcept = default;
    +  };
    +}
    +
    +
+
+
+

Insert a new subclause, Class inplace_stop_token [stoptoken.inplace], after the subclause added above, as a new subclause +of Stop tokens [thread.stoptoken].

+
+
+

33.3.8. Class inplace_stop_token [stoptoken.inplace]

+
33.3.8.1. General [stoptoken.inplace.general]
+
    +
  1. +

    The class inplace_stop_token models the concept stoppable_token. It +references the stop state of its associated inplace_stop_source object +([stopsource.inplace]), if any.

    +
    namespace std {
    +  class inplace_stop_token {
    +  public:
    +    template<class CB>
    +      using callback_type = inplace_stop_callback<CB>;
    +
    +    inplace_stop_token() noexcept = default;
    +    bool operator==(const inplace_stop_token&) const noexcept = default;
    +
    +    // [stoptoken.inplace.mem], member functions
    +    bool stop_requested() const noexcept;
    +    bool stop_possible() const noexcept;
    +    void swap(inplace_stop_token&) noexcept;
    +
    +  private:
    +    const inplace_stop_source* stop-source = nullptr; // exposition only
    +  };
    +}
    +
    +
+
33.3.8.2. Member functions [stoptoken.inplace.members]
+
void swap(inplace_stop_token& rhs) noexcept;
+
+
    +
  1. +

    Effects: Exchanges the values of stop-source and rhs.stop-source.

    +
+
bool stop_requested() const noexcept;
+
+
    +
  1. +

    Effects: Equivalent to: return stop-source != nullptr && stop-source->stop_requested();

    +
  2. +

    As specified in [basic.life], the behavior of stop_requested() is undefined unless the call strongly happens before the +start of the destructor of the associated inplace_stop_source, if +any.

    +
+
bool stop_possible() const noexcept;
+
+
    +
  1. +

    Returns: stop-source != nullptr.

    +
  2. +

    As specified in [basic.stc.general], the behavior of stop_possible() is implementation-defined unless the call strongly happens +before the end of the storage duration of the associated inplace_stop_source object, if any.

    +
+
+
+

Insert a new subclause, Class inplace_stop_source [stopsource.inplace], after the subclause added above, as a new subclause +of Stop tokens [thread.stoptoken].

+
+
+

33.3.9. Class inplace_stop_source [stopsource.inplace]

+
33.3.9.1. General [stopsource.inplace.general]
+
    +
  1. +

    The class inplace_stop_source models stoppable-source. Unlike stop_source, inplace_stop_source does not require dynamic allocation or +reference counting of a shared stop state. Instead, it requires that all +uses of associated inplace_stop_token and inplace_stop_callback objects happen before the inplace_stop_source is destroyed.

    +
    namespace std {
    +  class inplace_stop_source {
    +  public:
    +    // [stopsource.inplace.cons], constructors, copy, and assignment
    +    inplace_stop_source() noexcept;
    +
    +    inplace_stop_source(inplace_stop_source&&) = delete;
    +    inplace_stop_source(const inplace_stop_source&) = delete;
    +    inplace_stop_source& operator=(inplace_stop_source&&) = delete;
    +    inplace_stop_source& operator=(const inplace_stop_source&) = delete;
    +    ~inplace_stop_source();
    +
    +    //[stopsource.inplace.mem], stop handling
    +    inplace_stop_token get_token() const noexcept;
    +    static constexpr bool stop_possible() noexcept { return true; }
    +    bool stop_requested() const noexcept;
    +    bool request_stop() noexcept;
    +  };
    +}
    +
    +
+
33.3.9.2. Constructors, copy, and assignment [stopsource.inplace.cons]
+
inplace_stop_source() noexcept;
+
+
    +
  1. +

    Effects: Initializes a new stop state inside *this.

    +
  2. +

    Postconditions: stop_requested() is false.

    +
+
33.3.9.3. Members [stopsource.inplace.mem]
+
inplace_stop_token get_token() const noexcept;
+
+
    +
  1. +

    Returns: A new associated inplace_stop_token object.

    +
+
bool stop_requested() const noexcept;
+
+
    +
  1. +

    Returns: true if the stop state inside *this has received a stop +request; otherwise, false.

    +
+
bool request_stop() noexcept;
+
+
    +
  1. +

    Effects: Executes a stop request operation ([stoptoken.concepts]).

    +
  2. +

    Postconditions: stop_requested() is true.

    +
+
+
+

Insert a new subclause, Class template inplace_stop_callback [stopcallback.inplace], after the subclause +added above, as a new subclause of Stop tokens [thread.stoptoken].

+
+
+

33.3.10. Class template inplace_stop_callback [stopcallback.inplace]

+
33.3.10.1. General [stopcallback.inplace.general]
+
    +
  1. +
    namespace std {
    +  template<class Callback>
    +  class inplace_stop_callback {
    +  public:
    +    using callback_type = Callback;
    +
    +    // [stopcallback.inplace.cons], constructors and destructor
    +    template<class C>
    +      explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
    +        noexcept(is_nothrow_constructible_v<Callback, C>);
    +    ~inplace_stop_callback();
    +
    +    inplace_stop_callback(inplace_stop_callback&&) = delete;
    +    inplace_stop_callback(const inplace_stop_callback&) = delete;
    +    inplace_stop_callback& operator=(inplace_stop_callback&&) = delete;
    +    inplace_stop_callback& operator=(const inplace_stop_callback&) = delete;
    +
    +  private:
    +    Callback stop-callback;      // exposition only
    +  };
    +
    +  template<class Callback>
    +    inplace_stop_callback(inplace_stop_token, Callback)
    +      -> inplace_stop_callback<Callback>;
    +}
    +
    +
  2. +

    Mandates: inplace_stop_callback is instantiated with an argument for the +template parameter Callback that satisfies both invocable and destructible.

    +
  3. +

    Remarks: For a type C, if stoppable-callback-for<Callback, inplace_stop_token, C> is satisfied, then stoppable-callback-for<Callback, inplace_stop_token, C> is modeled. The exposition-only stop-callback member is +the associated callback function ([stoptoken.concepts]) of inplace_stop_callback<Callback> objects.

    +

    Implementations are not permitted to use additional storage, such +as dynamic memory, to store the state necessary for an inplace_stop_callback's association with an inplace_stop_source object +or to register the callback invocation with the associated inplace_stop_source object.

    +
+
33.3.10.2. Constructors and destructor [stopcallback.inplace.cons]
+
template<class C>
+  explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
+    noexcept(is_nothrow_constructible_v<Callback, C>);
+
+
    +
  1. +

    Constraints: constructible_from<Callback, C> is satisfied.

    +
  2. +

    Effects: Initializes stop-callback with std::forward<C>(cb) and executes a stoppable callback registration +([stoptoken.concepts]).

    +
+
~inplace_stop_callback();
+
+
    +
  1. +

    Effects: Executes a stoppable callback deregistration +([stoptoken.concepts]).

    +
+
+
+

Insert a new top-level clause

+
+
+

34. Execution control library [exec]

+

34.1. General [exec.general]

+
    +
  1. +

    This Clause describes components supporting execution of function objects +[function.objects].

    +
  2. +

    The following subclauses describe the requirements, concepts, and components +for execution control primitives as summarized in Table 1.

    +
+ + + + + + + + + +
Table N: Execution control library summary [tab:execution.summary]
+ Subclause + Header +
[exec.sched] + Schedulers + <execution> +
[exec.recv] + Receivers + +
[exec.opstate] + Operation states + +
[exec.snd] + Senders + +
[exec.execute] + One-way execution + +
+
    +
  1. +

    [Note: A large number of execution control primitives are +customization point objects. For an object one might define multiple types of +customization point objects, for which different rules apply. Table 2 shows +the types of customization point objects used in the execution control +library:

    +
+ + + + + + + + +
Table N+1: Types of customization point objects in the execution control library [tab:execution.cpos]
Customization point object type + Purpose + Examples +
core + provide core execution functionality, and connection between core components + connect, start, execute +
completion functions + called by senders to announce the completion of the work (success, error, or cancellation) + set_value, set_error, set_stopped +
senders + allow the specialization of the provided sender algorithms + +
    +
  • sender factories (schedule, just, read, ...) +
  • sender adaptors (transfer, then, let_value, ...) +
  • sender consumers (start_detached, sync_wait) +
+
queries + allow querying different properties of objects + +
    +
  • general queries (get_allocator, get_stop_token, ...) +
  • environment queries (get_scheduler, get_delegatee_scheduler, ...) +
  • scheduler queries (get_forward_progress_guarantee, execute_may_block_caller, ...) +
  • sender attribute queries (get_completion_scheduler) +
+
+

-- end note]

+
    +
  1. +

    This clause makes use of the following exposition-only entities:

    +
      +
    1. +

      For a subexpression expr, let MANDATE-NOTHROW(expr) be expression-equivalent to expr.

      +
        +
      • +

        Mandates: noexcept(expr) is true.

        +
      +
    2. +
      namespace std {
      +  template<class T>
      +    concept movable-value =
      +      move_constructible<decay_t<T>> &&
      +      constructible_from<decay_t<T>, T> &&
      +      (!is_array_v<remove_cvref_t<T>>);
      +}
      +
      +
    3. +

      For function types F1 and F2 denoting R1(Args1...) and R2(Args2...) respectively, MATCHING-SIG(F1, F2) is true if and only if same_as<R1(Args&&...), R2(Args2&&...)> is true.

      +
    4. +

      For a subexpression err, let Err be decltype((err)) and let AS-EXCEPT-PTR(err) be:

      +
        +
      1. +

        err if decay_t<Err> denotes the type exception_ptr.

        +
          +
        • +

          Mandates: err != exception_ptr() is true

          +
        +
      2. +

        Otherwise, make_exception_ptr(system_error(err)) if decay_t<Err> denotes the type error_code,

        +
      3. +

        Otherwise, make_exception_ptr(err).

        +
      +
    +
+

34.2. Queries and queryables [exec.queryable]

+

34.2.1. General [exec.queryable.general]

+
    +
  1. +

    A queryable object is a read-only collection of +key/value pairs where each key is a customization point object known as a query object. A query is an invocation of a query object with a queryable +object as its first argument and a (possibly empty) set of additional +arguments. The result of a query expression is valid as long as the +queryable object is valid. A query imposes syntactic +and semantic requirements on its invocations.

    +
  2. +

    Given a subexpression env that refers to a queryable object o, a query +object q, and a (possibly empty) pack of subexpressions args, the expression q(env, args...) is equal to +([concepts.equality]) the expression q(c, args...) where c is a const lvalue reference to o.

    +
  3. +

    The type of a query expression can not be void.

    +
  4. +

    The expression q(env, args...) is equality-preserving +([concepts.equality]) and does not modify the function object or the +arguments.

    +
  5. +

    If the expression env.query(q, args...) is well-formed, +then it is expression-equivalent to q(env, args...).

    +
  6. +

    Unless otherwise specified, the value returned by the expression q(env, args...) is valid as long as env is valid.

    +
+

34.2.2. queryable concept [exec.queryable.concept]

+
namespace std {
+  template<class T>
+    concept queryable = destructible<T>;
+}
+
+
    +
  1. +

    The queryable concept specifies the constraints on the types of queryable +objects.

    +
  2. +

    Let env be an object of type Env. The type Env models queryable if +for each callable object q and a pack of subexpressions args, if requires { q(env, args...) } is true then q(env, args...) meets any semantic requirements imposed +by q.

    +
+

34.3. Asynchronous operations [async.ops]

+
    +
  1. +

    An execution resource is a program entity that manages +a (possibly dynamic) set of execution agents +([thread.req.lockable.general]), which it uses to execute parallel work on +behalf of callers. [Example 1: The currently active thread, a +system-provided thread pool, and uses of an API associated with an external +hardware accelerator are all examples of execution resources. -- end +example] Execution resources execute asynchronous operations. An execution +resource is either valid or invalid.

    +
  2. +

    An asynchronous operation is a distinct unit of +program execution that:

    +
      +
    • +

      is explicitly created;

      +
    • +

      can be explicitly started; an + asynchronous operation can be started once at most;

      +
    • +

      if started, eventually completes with a (possibly empty) set of result datums, and in exactly one of + three modes: success, failure, or cancellation, known as the + operation’s disposition; an asychronous + operation can only complete once; a successful completion, also known + as a value completion, can have an arbitrary + number of result datums; a failure completion, also known as an error completion, has a single result datum; a + cancellation completion, also known as a stopped + completion, has no result datum; an asynchronous operation’s async result is its disposition and its + (possibly empty) set of result datums.

      +
    • +

      can complete on a different execution resource than that on which it + started; and

      +
    • +

      can create and start other asychronous operations called child operations. A child operation is an + asynchronous operation that is created by the parent operation and, if + started, completes before the parent operation completes. A parent operation is the asynchronous operation that + created a particular child operation.

      +
    +

    An asynchronous operation can in fact execute +synchronously; that is, it can complete during the execution of its start +operation on the thread of execution that started it.

    +
  3. +

    An asynchronous operation has associated state known as its operation state.

    +
  4. +

    An asynchronous operation has an associated environment. An environment is a queryable object ([exec.queryable]) +representing the execution-time properties of the operation’s caller. The caller of an asynchronous operation is +its parent operation or the function that created it. An asynchronous +operation’s operation state owns the operation’s environment.

    +
  5. +

    An asynchronous operation has an associated receiver. A receiver is an aggregation of three handlers for the three +asynchronous completion dispositions: a value completion handler for a value +completion, an error completion handler for an error completion, and a +stopped completion handler for a stopped completion. A receiver has an +associated environment. An asynchronous operation’s operation state owns the +operation’s receiver. The environment of an asynchronous operation is equal +to its receiver’s environment.

    +
  6. +

    For each completion disposition, there is a completion +function. A completion function is a customization point object +([customization.point.object]) that accepts an asynchronous operation’s +receiver as the first argument and the result datums of the asynchronous +operation as additional arguments. The value completion function invokes the +receiver’s value completion handler with the value result datums; likewise +for the error completion function and the stopped completion function. A +completion function has an associated type known as its completion tag that names the unqualified type of the +completion function. A valid invocation of a completion function is called a completion operation.

    +
  7. +

    The lifetime of an +asynchronous operation, also known as the operation’s async lifetime, begins when its start operation begins +executing and ends when its completion operation begins executing. If the +lifetime of an asynchronous operation’s associated operation state ends +before the lifetime of the asynchronous operation, the behavior is +undefined. After an asynchronous operation executes a completion operation, +its associated operation state is invalid. Accessing any part of an invalid +operation state is undefined behavior.

    +
  8. +

    An asynchronous operation shall not execute a completion operation before its +start operation has begun executing. After its start operation has begun +executing, exactly one completion operation shall execute. The lifetime of an +asynchronous operation’s operation state can end during the execution of the +completion operation.

    +
  9. +

    A sender is a factory for one or more asynchronous +operations. Connecting a sender and a +receiver creates an asynchronous operation. The asynchronous operation’s +associated receiver is equal to the receiver used to create it, and its +associated environment is equal to the environment associated with the +receiver used to create it. The lifetime of an asynchronous operation’s +associated operation state does not depend on the lifetimes of either the +sender or the receiver from which it was created. A sender sends its results by way of the asynchronous operation(s) +it produces, and a receiver receives those results. A sender is either valid or invalid; it becomes invalid +when its parent sender (see below) becomes invalid.

    +
  10. +

    A scheduler is an abstraction of an execution +resource with a uniform, generic interface for scheduling work onto that +resource. It is a factory for senders whose asynchronous operations execute +value completion operations on an execution agent belonging to the +scheduler’s associated execution resource. A schedule-expression obtains such a sender from a +scheduler. A schedule sender is the result of a +schedule expression. On success, an asynchronous operation produced by a +schedule sender executes a value completion operation with an empty set of +result datums. Multiple schedulers can refer to the same execution resource. +A scheduler can be valid or invalid. A scheduler becomes invalid when the +execution resource to which it refers becomes invalid, as do any schedule +senders obtained from the scheduler, and any operation states obtained from +those senders.

    +
  11. +

    An asynchronous operation has one or more associated completion schedulers +for each of its possible dispositions. A completion +scheduler is a scheduler whose associated execution resource is used +to execute a completion operation for an asynchronous operation. A value +completion scheduler is a scheduler on which an asynchronous operation’s +value completion operation can execute. Likewise for error completion +schedulers and stopped completion schedulers.

    +
  12. +

    A sender has an associated queryable object ([exec.queryable]) known as its attributes that describes various characteristics of +the sender and of the asynchronous operation(s) it produces. For each +disposition, there is a query object for reading the associated completion +scheduler from a sender’s attributes; i.e., a value completion scheduler +query object for reading a sender’s value completion scheduler, etc. If a +completion scheduler query is well-formed, the returned completion scheduler +is unique for that disposition for any asynchronous operation the sender +creates. A schedule sender is required to have a value completion scheduler +attribute whose value is equal to the scheduler that produced the schedule +sender.

    +
  13. +

    A completion signature is a function type that +describes a completion operation. An asychronous operation has a finite set +of possible completion signatures corresponding to the completion operations +that the asynchronous operation potentially evaluates ([basic.def.odr]). For +a completion function set, receiver rcvr, and pack of arguments args, +let c be the completion operation set(rcvr, args...), and let F be the function type decltype(auto(set))(decltype((args))...). +A completion signature Sig is associated with c if and only if MATCHING-SIG(Sig, F) is true ([exec.general]). Together, +a sender type and an environment type Env determine the set of completion +signatures of an asynchronous operation that results from connecting the +sender with a receiver that has an environment of type Env. The type of the receiver does not affect an asychronous +operation’s completion signatures, only the type of the receiver’s +environment.

    +
  14. +

    A sender algorithm is a function that takes and/or +returns a sender. There are three categories of sender algorithms:

    +
      +
    • +

      A sender factory is a function that takes +non-senders as arguments and that returns a sender.

      +
    • +

      A sender adaptor is a function that constructs and +returns a parent sender from a set of one or more child senders and a (possibly +empty) set of additional arguments. An asynchronous operation created by +a parent sender is a parent operation to the child operations created by +the child senders.

      +
    • +

      A sender consumer is a function that takes one or +more senders and a (possibly empty) set of additional arguments, and +whose return type is not the type of a sender.

      +
    +
+

34.4. Header <execution> synopsis [exec.syn]

+
namespace std {
+  // [exec.general], helper concepts
+  template<class T>
+    concept movable-value = see below; // exposition only
+
+  template<class From, class To>
+    concept decays-to = same_as<decay_t<From>, To>; // exposition only
+
+  template<class T>
+    concept class-type = decays-to<T, T> && is_class_v<T>;  // exposition only
+
+  // [exec.queryable], queryable objects
+  template<class T>
+    concept queryable = destructible<T>;
+
+  // [exec.queries], queries
+  struct forwarding_query_t;
+  struct get_allocator_t;
+  struct get_stop_token_t;
+
+  inline constexpr forwarding_query_t forwarding_query{};
+  inline constexpr get_allocator_t get_allocator{};
+  inline constexpr get_stop_token_t get_stop_token{};
+
+  template<class T>
+    using stop_token_of_t =
+      remove_cvref_t<decltype(get_stop_token(declval<T>()))>;
+
+  template<class T>
+    concept forwarding-query = // exposition only
+      forwarding_query(T{});
+}
+
+namespace std::execution {
+  // [exec.queries], queries
+  enum class forward_progress_guarantee;
+  struct get_domain_t;
+  struct get_scheduler_t;
+  struct get_delegatee_scheduler_t;
+  struct get_forward_progress_guarantee_t;
+  template<class CPO>
+    struct get_completion_scheduler_t;
+
+  inline constexpr get_domain_t get_domain{};
+  inline constexpr get_scheduler_t get_scheduler{};
+  inline constexpr get_delegatee_scheduler_t get_delegatee_scheduler{};
+  inline constexpr get_forward_progress_guarantee_t get_forward_progress_guarantee{};
+  template<class CPO>
+    inline constexpr get_completion_scheduler_t<CPO> get_completion_scheduler{};
+
+  struct empty_env {};
+  struct get_env_t;
+  inline constexpr get_env_t get_env {};
+
+  template<class T>
+    using env_of_t = decltype(get_env(declval<T>()));
+
+  // [exec.domain.default], execution domains
+  struct default_domain;
+
+  // [exec.sched], schedulers
+  struct scheduler_t {};
+
+  template<class Sch>
+    concept scheduler = see below;
+
+  // [exec.recv], receivers
+  struct receiver_t {};
+
+  template<class Rcvr>
+    concept receiver = see below;
+
+  template<class Rcvr, class Completions>
+    concept receiver_of = see below;
+
+  struct set_value_t;
+  struct set_error_t;
+  struct set_stopped_t;
+
+  inline constexpr set_value_t set_value{};
+  inline constexpr set_error_t set_error{};
+  inline constexpr set_stopped_t set_stopped{};
+
+  // [exec.opstate], operation states
+  struct operation_state_t {};
+
+  template<class O>
+    concept operation_state = see below;
+
+  struct start_t;
+  inline constexpr start_t start{};
+
+  // [exec.snd], senders
+  struct sender_t {};
+
+  template<class Sndr>
+    concept sender = see below;
+
+  template<class Sndr, class Env = empty_env>
+    concept sender_in = see below;
+
+  template<class Sndr, class Rcvr>
+    concept sender_to = see below;
+
+  template<class... Ts>
+    struct type-list; // exposition only
+
+  template<class Sndr, class Env = empty_env>
+    using single-sender-value-type = see below; // exposition only
+
+  template<class Sndr, class Env = empty_env>
+    concept single-sender = see below; // exposition only
+
+  // [exec.getcomplsigs], completion signatures
+  struct get_completion_signatures_t;
+  inline constexpr get_completion_signatures_t get_completion_signatures {};
+
+  template<class Sndr, class Env = empty_env>
+      requires sender_in<Sndr, Env>
+    using completion_signatures_of_t = call-result-t<get_completion_signatures_t, Sndr, Env>;
+
+  template<class... Ts>
+    using decayed-tuple = tuple<decay_t<Ts>...>; // exposition only
+
+  template<class... Ts>
+    using variant-or-empty = see below; // exposition only
+
+  template<class Sndr,
+           class Env = empty_env,
+           template<class...> class Tuple = decayed-tuple,
+           template<class...> class Variant = variant-or-empty>
+      requires sender_in<Sndr, Env>
+    using value_types_of_t = see below;
+
+  template<class Sndr,
+           class Env = empty_env,
+           template<class...> class Variant = variant-or-empty>
+      requires sender_in<Sndr, Env>
+    using error_types_of_t = see below;
+
+  template<class Sndr, class Env = empty_env>
+      requires sender_in<Sndr, Env>
+    inline constexpr bool sends_stopped = see below;
+
+  template <sender Sndr>
+    using tag_of_t = see below;
+
+  // [exec.snd.transform], sender transformations
+  template<class Domain, sender Sndr, queryable... Env>
+      requires (sizeof...(Env) <= 1)
+    constexpr sender decltype(auto) transform_sender(
+      Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below);
+
+  // [exec.snd.transform.env], environment transformations
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr queryable decltype(auto) transform_env(
+      Domain dom, Sndr&& sndr, Env&& env) noexcept;
+
+  // [exec.snd.apply], sender algorithm application
+  template<class Domain, class Tag, sender Sndr, class... Args>
+    constexpr decltype(auto) apply_sender(
+      Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below);
+
+  // [exec.connect], the connect sender algorithm
+  struct connect_t;
+  inline constexpr connect_t connect{};
+
+  template<class Sndr, class Rcvr>
+    using connect_result_t =
+      decltype(connect(declval<Sndr>(), declval<Rcvr>()));
+
+  // [exec.factories], sender factories
+  struct just_t;
+  struct just_error_t;
+  struct just_stopped_t;
+  struct schedule_t;
+
+  inline constexpr just_t just{};
+  inline constexpr just_error_t just_error{};
+  inline constexpr just_stopped_t just_stopped{};
+  inline constexpr schedule_t schedule{};
+  inline constexpr unspecified read{};
+
+  template<scheduler Sndr>
+    using schedule_result_t = decltype(schedule(declval<Sndr>()));
+
+  // [exec.adapt], sender adaptors
+  template<class-type D>
+    struct sender_adaptor_closure { };
+
+  struct on_t;
+  struct transfer_t;
+  struct schedule_from_t;
+  struct then_t;
+  struct upon_error_t;
+  struct upon_stopped_t;
+  struct let_value_t;
+  struct let_error_t;
+  struct let_stopped_t;
+  struct bulk_t;
+  struct split_t;
+  struct ensure_started_t;
+  struct when_all_t;
+  struct when_all_with_variant_t;
+  struct into_variant_t;
+  struct stopped_as_optional_t;
+  struct stopped_as_error_t;
+
+  inline constexpr on_t on{};
+  inline constexpr transfer_t transfer{};
+  inline constexpr schedule_from_t schedule_from{};
+  inline constexpr then_t then{};
+  inline constexpr upon_error_t upon_error{};
+  inline constexpr upon_stopped_t upon_stopped{};
+  inline constexpr let_value_t let_value{};
+  inline constexpr let_error_t let_error{};
+  inline constexpr let_stopped_t let_stopped{};
+  inline constexpr bulk_t bulk{};
+  inline constexpr split_t split{};
+  inline constexpr ensure_started_t ensure_started{};
+  inline constexpr when_all_t when_all{};
+  inline constexpr when_all_with_variant_t when_all_with_variant{};
+  inline constexpr into_variant_t into_variant{};
+  inline constexpr stopped_as_optional_t stopped_as_optional;
+  inline constexpr stopped_as_error_t stopped_as_error;
+
+  // [exec.consumers], sender consumers
+  struct start_detached_t;
+  inline constexpr start_detached_t start_detached{};
+
+  // [exec.utils], sender and receiver utilities
+  // [exec.utils.cmplsigs]
+  template<class Fn>
+    concept completion-signature = // exposition only
+      see below;
+
+  template<completion-signature... Fns>
+    struct completion_signatures {};
+
+  template<class Sigs> // exposition only
+    concept valid-completion-signatures = see below;
+
+  // [exec.utils.tfxcmplsigs]
+  template<
+    valid-completion-signatures InputSignatures,
+    valid-completion-signatures AdditionalSignatures = completion_signatures<>,
+    template<class...> class SetValue = see below,
+    template<class> class SetError = see below,
+    valid-completion-signatures SetStopped = completion_signatures<set_stopped_t()>>
+  using transform_completion_signatures = completion_signatures<see below>;
+
+  template<
+    sender Sndr,
+    class Env = empty_env,
+    valid-completion-signatures AdditionalSignatures = completion_signatures<>,
+    template<class...> class SetValue = see below,
+    template<class> class SetError = see below,
+    valid-completion-signatures SetStopped = completion_signatures<set_stopped_t()>>
+      requires sender_in<Sndr, Env>
+  using transform_completion_signatures_of =
+    transform_completion_signatures<
+      completion_signatures_of_t<Sndr, Env>,
+      AdditionalSignatures, SetValue, SetError, SetStopped>;
+
+  // [exec.ctx], execution resources
+  // [exec.run.loop], run_loop
+  class run_loop;
+}
+
+namespace std::this_thread {
+  // [exec.queries], queries
+  struct execute_may_block_caller_t;
+  inline constexpr execute_may_block_caller_t execute_may_block_caller{};
+
+  struct sync_wait_t;
+  struct sync_wait_with_variant_t;
+
+  inline constexpr sync_wait_t sync_wait{};
+  inline constexpr sync_wait_with_variant_t sync_wait_with_variant{};
+}
+
+namespace std::execution {
+  // [exec.execute], one-way execution
+  struct execute_t;
+  inline constexpr execute_t execute{};
+
+  // [exec.as.awaitable]
+  struct as_awaitable_t;
+  inline constexpr as_awaitable_t as_awaitable;
+
+  // [exec.with.awaitable.senders]
+  template<class-type Promise>
+    struct with_awaitable_senders;
+}
+
+
    +
  1. +

    The exposition-only type variant-or-empty<Ts...> is + defined as follows:

    +
      +
    1. +

      If sizeof...(Ts) is greater than zero, variant-or-empty<Ts...> names the type variant<Us...> where Us... is the pack decay_t<Ts>... with +duplicate types removed.

      +
    2. +

      Otherwise, variant-or-empty<Ts...> names the +exposition-only class type:

      +
      namespace std::execution {
      +  struct empty-variant {
      +    empty-variant() = delete;
      +  };
      +}
      +
      +
    +
+

34.5. Queries [exec.queries]

+

34.5.1. std::forwarding_query [exec.fwd.env]

+
    +
  1. +

    forwarding_query asks a query object whether it should be forwarded +through queryable adaptors.

    +
  2. +

    The name forwarding_query denotes a query object. For some query +object q of type Q, forwarding_query(q) is expression-equivalent +to:

    +
      +
    1. +

      MANDATE-NOTHROW(q.query(forwarding_query)) if that +expression is well-formed.

      +
        +
      • +

        Mandates: The expression above has type bool and is a core +constant expressions if q is a core constant expression.

        +
      +
    2. +

      Otherwise, true if derived_from<Q, forwarding_query_t> is true.

      +
    3. +

      Otherwise, false.

      +
    +
+

34.5.2. std::get_allocator [exec.get.allocator]

+
    +
  1. +

    get_allocator asks an object for its associated allocator.

    +
  2. +

    The name get_allocator denotes a query object. For a subexpression env, get_allocator(env) is expression-equivalent to MANDATE-NOTHROW(as_const(env).query(get_allocator)).

    +
      +
    • +

      Mandates: If the expression above is well-formed, its type + satisfies Allocator.

      +
    +
  3. +

    forwarding_query(get_allocator) is a core constant +expression and has value true.

    +
  4. +

    get_allocator() (with no arguments) is expression-equivalent to execution::read(get_allocator) ([exec.read]).

    +
+

34.5.3. std::get_stop_token [exec.get.stop.token]

+
    +
  1. +

    get_stop_token asks an object for an associated stop token.

    +
  2. +

    The name get_stop_token denotes a query object. For a subexpression env, get_stop_token(env) is expression-equivalent to:

    +
      +
    1. +

      MANDATE-NOTHROW(as_const(env).query(get_stop_token)) if that expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above satisfies stoppable_token.

        +
      +
    2. +

      Otherwise, never_stop_token{}.

      +
    +
  3. +

    forwarding_query(get_stop_token) is a core constant +expression and has value true.

    +
  4. +

    get_stop_token() (with no arguments) is expression-equivalent to execution::read(get_stop_token) ([exec.read]).

    +
+

34.5.4. execution::get_env [exec.get.env]

+
    +
  1. +

    execution::get_env is a customization point object. For a subexpression o, execution::get_env(o) is expression-equivalent to:

    +
      +
    1. +

      as_const(o).get_env() if that expression is +well-formed.

      +
        +
      • +

        Mandates: The expression above is not potentially throwing, and +its type satisfies queryable ([exec.queryable]).

        +
      +
    2. +

      Otherwise, empty_env{}.

      +
    +
  2. +

    The value of get_env(o) shall be valid while o is valid.

    +
  3. +

    When passed a sender object, get_env returns the +sender’s attributes. When passed a receiver, get_env returns the +receiver’s environment.

    +
+

34.5.5. execution::get_domain [exec.get.domain]

+
    +
  1. +

    get_domain asks an object for an associated execution domain tag.

    +
  2. +

    The name get_domain denotes a query object. For a subexpression env, get_domain(env) is expression-equivalent to MANDATE-NOTHROW(as_const(env).query(get_domain)).

    +
  3. +

    forwarding_query(execution::get_domain) is a core constant +expression and has value true.

    +
  4. +

    get_domain() (with no arguments) is expression-equivalent to execution::read(get_domain) ([exec.read]).

    +
+

34.5.6. execution::get_scheduler [exec.get.scheduler]

+
    +
  1. +

    get_scheduler asks an object for its associated scheduler.

    +
  2. +

    The name get_scheduler denotes a query object. For a +subexpression env, get_scheduler(env) is expression-equivalent to MANDATE-NOTHROW(as_const(env).query(get_scheduler)).

    +
      +
    • +

      Mandates: If the expression above is well-formed, its type + satisfies scheduler.

      +
    +
  3. +

    forwarding_query(execution::get_scheduler) is a core constant +expression and has value true.

    +
  4. +

    get_scheduler() (with no arguments) is expression-equivalent to execution::read(get_scheduler) ([exec.read]).

    +
+

34.5.7. execution::get_delegatee_scheduler [exec.get.delegatee.scheduler]

+
    +
  1. +

    get_delegatee_scheduler asks an object for a scheduler that can be used to +delegate work to for the purpose of forward progress delegation.

    +
  2. +

    The name get_delegatee_scheduler denotes a query object. For a +subexpression env, get_delegatee_scheduler(env) is expression-equivalent to MANDATE-NOTHROW(as_const(env).query(get_delegatee_scheduler)).

    +
      +
    • +

      Mandates: If the expression above is well-formed, its type + satisfies scheduler.

      +
    +
  3. +

    forwarding_query(execution::get_delegatee_scheduler) is a core +constant expression and has value true.

    +
  4. +

    get_delegatee_scheduler() (with no arguments) is expression-equivalent to execution::read(get_delegatee_scheduler) ([exec.read]).

    +
+

34.5.8. execution::get_forward_progress_guarantee [exec.get.forward.progress.guarantee]

+
namespace std::execution {
+  enum class forward_progress_guarantee {
+    concurrent,
+    parallel,
+    weakly_parallel
+  };
+}
+
+
    +
  1. +

    get_forward_progress_guarantee asks a scheduler about the forward progress +guarantee of execution agents created by that scheduler.

    +
  2. +

    The name get_forward_progress_guarantee denotes a query object. For a +subexpression sch, let Sch be decltype((sch)). If Sch does not +satisfy scheduler, get_forward_progress_guarantee is ill-formed. +Otherwise, get_forward_progress_guarantee(sch) is expression-equivalent +to:

    +
      +
    1. +

      MANDATE-NOTHROW(as_const(sch).query(get_forward_progress_guarantee)), +if this expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above is forward_progress_guarantee.

        +
      +
    2. +

      Otherwise, forward_progress_guarantee::weakly_parallel.

      +
    +
  3. +

    If get_forward_progress_guarantee(sch) for some scheduler sch returns forward_progress_guarantee::concurrent, all execution agents created by +that scheduler shall provide the concurrent forward progress guarantee. If +it returns forward_progress_guarantee::parallel, all execution agents +created by that scheduler shall provide at least the parallel forward +progress guarantee.

    +
+

34.5.9. this_thread::execute_may_block_caller [exec.execute.may.block.caller]

+
    +
  1. +

    this_thread::execute_may_block_caller asks a scheduler sch whether a call execute(sch, f) with any invocable f may block the thread where such a +call occurs.

    +
  2. +

    The name this_thread::execute_may_block_caller denotes a query object. For +a subexpression sch, let Sch be decltype((sch)). If Sch does not +satisfy scheduler, this_thread::execute_may_block_caller is ill-formed. +Otherwise, this_thread::execute_may_block_caller(sch) is +expression-equivalent to:

    +
      +
    1. +

      MANDATE-NOTHROW(as_const(sch).query(this_thread::execute_may_block_caller)), +if this expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above is bool.

        +
      +
    2. +

      Otherwise, true.

      +
    +
  3. +

    If this_thread::execute_may_block_caller(sch) for some scheduler sch returns false, no execute(sch, f) call with some invocable f shall +block the calling thread.

    +
+

34.5.10. execution::get_completion_scheduler [exec.completion.scheduler]

+
    +
  1. +

    get_completion_scheduler<completion-tag> obtains the +completion scheduler associated with a completion tag from a sender’s +attributes.

    +
  2. +

    The name get_completion_scheduler denotes a query object template. For a +subexpression q, let Q be decltype((q)). If the template argument Tag in get_completion_scheduler<Tag>(q) is not one of set_value_t, set_error_t, or set_stopped_t, get_completion_scheduler<Tag>(q) is +ill-formed. Otherwise, get_completion_scheduler<Tag>(q) is +expression-equivalent to MANDATE-NOTHROW(as_const(q).query(get_completion_scheduler<Tag>)).

    +
      +
    • +

      Mandates: If the expression above is well-formed, its type + satisfies scheduler.

      +
    +
  3. +

    If, for some sender sndr and completion function C that has an associated +completion tag Tag, get_completion_scheduler<Tag>(get_env(sndr)) is +well-formed and results in a scheduler sch, and the sender sndr invokes C(rcvr, args...), for some receiver rcvr that has been connected to sndr, with +additional arguments args..., on an execution agent that does not +belong to the associated execution resource of sch, the behavior is +undefined.

    +
  4. +

    The expression forwarding_query(get_completion_scheduler<CPO>) is a core constant expression and has value true.

    +
+

34.6. Schedulers [exec.sched]

+
    +
  1. +

    The scheduler concept defines the requirements of a scheduler type +([async.ops]). schedule is a customization point object that accepts a +scheduler. A valid invocation of schedule is a schedule-expression.

    +
    namespace std::execution {
    +  template<class Sch>
    +    concept enable-scheduler = // exposition only
    +      requires {
    +        requires derived_from<typename Sch::scheduler_concept, scheduler_t>;
    +      };
    +
    +  template<class Sch>
    +    concept scheduler =
    +      enable-scheduler<remove_cvref_t<Sch>> &&
    +      queryable<Sch> &&
    +      requires(Sch&& sch) {
    +        { schedule(std::forward<Sch>(sch)) } -> sender;
    +        { get_completion_scheduler<set_value_t>(
    +            get_env(schedule(std::forward<Sch>(sch)))) }
    +              -> same_as<remove_cvref_t<Sch>>;
    +      } &&
    +      equality_comparable<remove_cvref_t<Sch>> &&
    +      copy_constructible<remove_cvref_t<Sch>>;
    +}
    +
    +
  2. +

    Let Sch be the type of a scheduler and let Env be the type of an execution +environment for which sender_in<schedule_result_t<Sch>, Env> is true. Then sender-of-in<schedule_result_t<Sch>, Env> shall be true.

    +
  3. +

    None of a scheduler’s copy constructor, destructor, equality comparison, or swap member functions shall exit via an exception.

    +
  4. +

    None of these member functions, nor a scheduler type’s schedule function, +shall introduce data races as a result of concurrent invocations of those +functions from different threads.

    +
  5. +

    For any two (possibly const) values sch1 and sch2 of some scheduler type Sch, sch1 == sch2 shall return true only if both sch1 and sch2 share the +same associated execution resource.

    +
  6. +

    For a given scheduler expression sch, the expression get_completion_scheduler<set_value_t>(get_env(schedule(sch))) shall +compare equal to sch.

    +
  7. +

    For a given scheduler expression sch, if the expression get_domain(sch) is well-formed, then the expression get_domain(get_env(schedule(sch))) is also well-formed and has the same type.

    +
  8. +

    A scheduler type’s destructor shall not block pending completion of any +receivers connected to the sender objects returned from schedule. The ability to wait for completion of submitted function +objects can be provided by the associated execution resource of the +scheduler.

    +
+

34.7. Receivers [exec.recv]

+

34.7.1. Receiver concepts [exec.recv.concepts]

+
    +
  1. +

    A receiver represents the continuation of an asynchronous operation. The receiver concept defines the requirements for a receiver type +([async.ops]). The receiver_of concept defines the requirements for a +receiver type that is usable as the first argument of a set of completion +operations corresponding to a set of completion signatures. The get_env customization point is used to access a receiver’s associated environment.

    +
    namespace std::execution {
    +  template<class Rcvr>
    +    concept enable-receiver = // exposition only
    +      requires {
    +        requires derived_from<typename Rcvr::receiver_concept, receiver_t>;
    +      };
    +
    +  template<class Rcvr>
    +    concept receiver =
    +      enable-receiver<remove_cvref_t<Rcvr>> &&
    +      requires(const remove_cvref_t<Rcvr>& rcvr) {
    +        { get_env(rcvr) } -> queryable;
    +      } &&
    +      move_constructible<remove_cvref_t<Rcvr>> &&  // rvalues are movable, and
    +      constructible_from<remove_cvref_t<Rcvr>, Rcvr>; // lvalues are copyable
    +
    +  template<class Signature, class Rcvr>
    +    concept valid-completion-for = // exposition only
    +      requires (Signature* sig) {
    +        []<class Tag, class... Args>(Tag(*)(Args...))
    +            requires callable<Tag, remove_cvref_t<Rcvr>, Args...>
    +        {}(sig);
    +      };
    +
    +  template<class Rcvr, class Completions>
    +    concept has-completions = // exposition only
    +      requires (Completions* completions) {
    +        []<valid-completion-for<Rcvr>...Sigs>(completion_signatures<Sigs...>*)
    +        {}(completions);
    +      };
    +
    +  template<class Rcvr, class Completions>
    +    concept receiver_of =
    +      receiver<Rcvr> && has-completions<Rcvr, Completions>;
    +}
    +
    +
  2. +

    Class types that are final do not model the receiver concept.

    +
  3. +

    Let rcvr be a receiver and let op_state be an operation state associated +with an asynchronous operation created by connecting rcvr with a sender. Let token be a stop token equal to get_stop_token(get_env(rcvr)). token shall +remain valid for the duration of the asynchronous operation’s lifetime +([async.ops]). This means that, unless it knows about +further guarantees provided by the type of receiver rcvr, the implementation +of op_state can not use token after it executes a completion operation. +This also implies that any stop callbacks registered on token must be +destroyed before the invocation of the completion operation.

    +
+

34.7.2. execution::set_value [exec.set.value]

+
    +
  1. +

    set_value is a value completion function ([async.ops]). Its associated +completion tag is set_value_t. The expression set_value(rcvr, vs...) for +a subexpression rcvr and pack of subexpressions vs is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is expression-equivalent to MANDATE-NOTHROW(rcvr.set_value(vs...)).

    +
+

34.7.3. execution::set_error [exec.set.error]

+
    +
  1. +

    set_error is an error completion function. Its associated completion tag is set_error_t. The expression set_error(rcvr, err) for some subexpressions rcvr and err is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is +expression-equivalent to MANDATE-NOTHROW(rcvr.set_error(err)).

    +
+

34.7.4. execution::set_stopped [exec.set.stopped]

+
    +
  1. +

    set_stopped is a stopped completion function. Its associated completion tag +is set_stopped_t. The expression set_stopped(rcvr) for a subexpression rcvr is ill-formed if rcvr is an lvalue or a const rvalue. Otherwise, it is +expression-equivalent to MANDATE-NOTHROW(rcvr.set_stopped()).

    +
+

34.8. Operation states [exec.opstate]

+
    +
  1. +

    The operation_state concept defines the requirements of an operation state +type ([async.ops]).

    +
    namespace std::execution {
    +  template<class Rcvr>
    +    concept enable-opstate = // exposition only
    +      requires {
    +        requires derived_from<typename Rcvr::operation_state_concept, operation_state_t>;
    +      };
    +
    +  template<class O>
    +    concept operation_state =
    +      enable-opstate<remove_cvref_t<O>> &&
    +      queryable<O> &&
    +      is_object_v<O> &&
    +      requires (O& o) {
    +        { start(o) } noexcept;
    +      };
    +}
    +
    +
  2. +

    If an operation_state object is moved during the lifetime of its +asynchronous operation ([async.ops]), the behavior is undefined.

    +
  3. +

    Library-provided operation state types are non-movable.

    +
+

34.8.1. execution::start [exec.opstate.start]

+
    +
  1. +

    The name start denotes a customization point object that starts +([async.ops]) the asynchronous operation associated with the operation state +object. For a subexpression op, the expression start(op) is ill-formed +if op is an rvalue. Otherwise, it is expression-equivalent to:

    +
    MANDATE-NOTHROW(op.start())
    +
    +
  2. +

    If op.start() does not start the asynchronous operation associated with the +operation state op, the behavior of calling start(op) is undefined.

    +
+

34.9. Senders [exec.snd]

+

34.9.1. General [exec.snd.general]

+
    +
  1. +

    For the purposes of this subclause, a sender is an object that satisfies the sender concept ([async.ops]).

    +
  2. +

    Subclauses [exec.factories] and [exec.adapt] define customizable algorithms +that return senders. Each algorithm has a default implementation. Let sndr be the result of an invocation of such an algorithm or an object equal to +such ([concepts.equality]), and let Sndr be decltype((sndr)). Let rcvr be a receiver with associated environment env of type Env such that sender_in<Sndr, Env> is true. For the default implementation of the +algorithm that produced sndr, connecting sndr to rcvr and starting the +resulting operation state ([async.ops]) necessarily results in the potential +evaluation ([basic.def.odr]) of a set of completion operations whose first +argument is a subexpression equal to rcvr. Let Sigs be a pack of +completion signatures corresponding to this set of completion operations. +Then the type of the expression get_completion_signatures(sndr, env) is a +specialization of the class template completion_signatures, +([exec.utils.cmplsigs]) the set of whose template arguments is Sigs. If a +user-provided implementation of the algorithm that produced sndr is +selected instead of the default, any completion signature that is in the set +of types denoted by completion_signatures_of_t<Sndr, Env> and that is not +part of Sigs shall correspond to error or stopped completion operations, +unless otherwise specified.

    +
  3. +

    This subclause makes use of the following exposition-only entities.

    +
      +
    1. +

      For a queryable object env, let FWD-ENV(env) be a +queryable object such that for a query object q and a pack of +subexpressions as, the expression FWD-ENV(env).query(q, as...) is ill-formed if forwarding_query(q) is false; +otherwise, it is expression-equivalent to env.query(q, as...).

      +
    2. +

      For a query object q and a subexpression v, let MAKE-ENV(q, v) be a queryable object env such that +the result of env.query(q) has a value equal to v ([concepts.equality]). Unless otherwise stated, the object to which env.query(q) refers remains valid while env remains valid.

      +
    3. +

      For two queryable objects env1 and env2, a query object q and a +pack of subexpressions as, let JOIN-ENV(env1, env2) be a queryable object env3 such that env3.query(q, as...) is expression-equivalent to:

      +
        +
      • +

        env1.query(q, as...) if that expression is well-formed,

        +
      • +

        otherwise, env2.query(q, as...) if that expression is + well-formed,

        +
      • +

        otherwise, env3.query(q, as...) is ill-formed.

        +
      +
    4. +

      The expansions of FWD-ENV, MAKE-ENV, and JOIN-ENV can be context-dependent; i.e., they can expand to +expressions with different types and value categories in different +contexts for the same arguments.

      +
    5. +

      For a scheduler sch, let SCHED-ATTRS(sch) be a +queryable object o1 such that o1.query(get_completion_scheduler<Tag>) is a +prvalue with the same type and value as sch where Tag is one +of set_value_t or set_stopped_t; and let o1.query(get_domain) be expression-equivalent to sch.query(get_domain). Let SCHED-ENV(sch) be a queryable object o2 such that o1.query(get_scheduler) is a prvalue with the same +type and value as sch, and let o2.query(get_domain) be expression-equivalent to sch.query(get_domain).

      +
    6. +

      For two subexpressions rcvr and expr, let SET-VALUE(rcvr, expr) be (expr, set_value(rcvr)) if the type of expr is void; +otherwise, it is set_value(rcvr, expr). Let TRY-EVAL(rcvr, expr) be:

      +
      try {
      +  expr;
      +} catch(...) {
      +  set_error(rcvr, current_exception());
      +}
      +
      +

      if expr is potentially-throwing; otherwise, expr. Let TRY-SET-VALUE(rcvr, expr) be TRY-EVAL(rcvr, SET-VALUE(rcvr, expr)) except that rcvr is evaluated only once.

      +
    7. +
      template<class Default = default_domain, class Sndr>
      +  constexpr auto completion-domain(const Sndr& sndr) noexcept;
      +
      +
        +
      1. +

        Effects: Let COMPL-DOMAIN(T) be the type of the +expression get_domain(get_completion_scheduler<T>(get_env(sndr))). +If COMPL-DOMAIN(set_value_t), COMPL-DOMAIN(set_error_t), and COMPL-DOMAIN(set_stopped_t) all share a common +type [meta.trans.other] (ignoring those types that are ill-formed), +then completion-domain<Default>(sndr) is a +default-constructed prvalue of that type. Otherwise, if all of those +types are ill-formed, completion-domain<Default>(sndr) is a +default-constructed prvalue of type Default. Otherwise, completion-domain<Default>(sndr) is +ill-formed.

        +
      +
    8. +
      template<class Tag, class Env, class Default>
      +  constexpr decltype(auto) query-with-default(
      +    Tag, const Env& env, Default&& value) noexcept(see below);
      +
      +
        +
      1. +

        Let e be the expression Tag()(env) if that +expression is well-formed; otherwise, it is static_cast<Default>(std::forward<Default>(value)).

        +
      2. +

        Returns: e.

        +
      3. +

        Remarks: The expression in the noexcept clause is noexcept(e).

        +
      +
    9. +
      template<class Sndr>
      +  constexpr auto get-domain-early(const Sndr& sndr) noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to return Domain(); where Domain is the decayed type of the first of the +following expressions that is well-formed:

        +
          +
        • +

          get_domain(get_env(sndr))

          +
        • +

          completion-domain(sndr)

          +
        • +

          default_domain()

          +
        +
      +
    10. +
      template<class Sndr, class Env>
      +  constexpr auto get-domain-late(const Sndr& sndr, const Env& env) noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to:

        +
          +
        • +

          If sender-for<Sndr, transfer_t> is true, +then return Domain(); where Domain is +the type of the following expression:

          +
          [] {
          +  auto [ignore1, sch, ignore2] = sndr;
          +  return query-or-default(get_domain, sch, default_domain());
          +}();
          +
          +
        • +

          Otherwise, return Domain(); where Domain is +the first of the following expressions that is well-formed and has class +type:

          +
            +
          • +

            get_domain(get_env(sndr))

            +
          • +

            completion-domain<void>(sndr)

            +
          • +

            get_domain(env)

            +
          • +

            get_domain(get_scheduler(env))

            +
          • +

            default_domain().

            +
          +
        +

        The transfer algorithm is unique in that it +ignores the execution domain of its predecessor, using only the +domain of its destination scheduler to select a +customization.

        +
      +
    11. +
      template<callable Fun>
      +  requires is_nothrow_move_constructible_v<Fun>
      +struct emplace-from { // exposition only
      +  Fun fun; // exposition only
      +  using type = call-result-t<Fun>;
      +
      +  constexpr operator type() && noexcept(nothrow-callable<Fun>) {
      +    return std::move(fun)();
      +  }
      +
      +  constexpr type operator()() && noexcept(nothrow-callable<Fun>) {
      +    return std::move(fun)();
      +  }
      +};
      +
      +
        +
      1. +

        emplace-from is used to emplace +non-movable types into containers like tuple, optional, and variant.

        +
      +
    12. +
      struct on-stop-request { // exposition only
      +  inplace_stop_source& stop-src; // exposition only
      +  void operator()() noexcept { stop-src.request_stop(); }
      +};
      +
      +
    13. +
      template<class... T>
      +struct product-type {  // exposition only
      +  using type0 = T0;      // exposition only
      +  using type1 = T1;      // exposition only
      +    ...
      +  using typen-1 = Tn-1;   // exposition only
      +
      +  T0 t0;      // exposition only
      +  T1 t1;      // exposition only
      +    ...
      +  Tn-1 tn-1;   // exposition only
      +};
      +
      +
        +
      1. +

        An expression of type product-type is usable as the initializer of a +structured binding declaration [dcl.struct.bind].

        +
      +
    14. +
      template <semiregular Tag, movable-value Data = see below, sender... Child>
      +  constexpr auto make-sender(Tag, Data&& data, Child&&... child);
      +
      +
        +
      1. +

        Returns: A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> where the tag member has been default-initialized and the data and childn... members have been direct +initialized from their respective forwarded arguments, where basic-sender is the following exposition-only +class template except as noted below:

        +
        namespace std::execution {
        +  template<class T, class... Us>
        +  concept one-of = (same_as<T, Us> ||...); // exposition only
        +
        +  template<class Tag>
        +  concept completion-tag = // exposition only
        +    one-of<Tag, set_value_t, set_error_t, set_stopped_t>;
        +
        +  template<template<class...> class T, class... Args>
        +  concept well-formed = requires { typename T<Args...>; }; // exposition only
        +
        +  template<const auto& Fun, class... Args>
        +  concept cpo-callable = callable<decltype(Fun), Args...>; // exposition only
        +
        +  template<const auto& Fun, class... Args>
        +  using cpo-result-t = call-result-t<decltype(Fun), Args...>; // exposition only
        +
        +  struct default-impls {  // exposition only
        +    static constexpr auto get-attrs = see below;
        +    static constexpr auto get-env = see below;
        +    static constexpr auto get-state = see below;
        +    static constexpr auto start = see below;
        +    static constexpr auto complete = see below;
        +  };
        +
        +  template<class Tag>
        +  struct impls-for : default-impls {}; // exposition only
        +
        +  template<class Sndr, class Rcvr> // exposition only
        +  using state-type = decay_t<cpo-result-t<
        +    impls-for<tag_of_t<Sndr>>::get-state, Sndr, Rcvr&>>;
        +
        +  template<class Index, class Sndr, class Rcvr> // exposition only
        +  using env-type = cpo-result-t<
        +    impls-for<tag_of_t<Sndr>>::get-env, Index,
        +    state-type<Sndr, Rcvr>&, const Rcvr&>>;
        +
        +  template<class Sndr, class Rcvr, class Index> 
        +    requires well-formed<env-type, Index, Sndr, Rcvr>
        +  struct basic-receiver {  // exposition only
        +    using receiver_concept = receiver_t;
        +
        +    using tag-type = tag_of_t<Sndr>; // exposition only
        +    using state-type = state-type<Sndr, Rcvr>; // exposition only
        +    static constexpr const auto& complete = impls-for<tag-type>::complete; // exposition only
        +
        +    template<class... Args>
        +      requires cpo-callable<complete, Index, state-type&, Rcvr&, set_value_t, Args...>
        +    void set_value(Args&&... args) && noexcept {
        +      complete(Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...);
        +    }
        +
        +    template<class Error>
        +      requires cpo-callable<complete, Index, state-type&, Rcvr&, set_error_t, Error>
        +    void set_error(Error&& err) && noexcept {
        +      complete(Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err));
        +    }
        +
        +    void set_stopped() && noexcept
        +      requires cpo-callable<complete, Index, state-type&, Rcvr&, set_stopped_t> {
        +      complete(Index(), op->state, op->rcvr, set_stopped_t());
        +    }
        +
        +    auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> {
        +      const auto& rcvr = op->rcvr;
        +      return impls-for<tag-type>::get-env(Index(), op->state, rcvr);
        +    }
        +
        +    basic-operation<Sndr, Rcvr>* op; // exposition only
        +  };
        +
        +  constexpr auto connect-all =   // exposition only
        +    []<class Sndr, class Rcvr, size_t... Is>(
        +      basic-operation<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>)
        +        noexcept( TODO ) requires ( TODO ) {
        +        auto&& [ign1, ign2, ...child] = std::forward<Sndr>(sndr);
        +        return product-type{connect(
        +          std::forward_like<Sndr>(child),
        +          basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
        +      };
        +
        +  template<class Sndr>
        +  using indices-for = make_index_sequence<tuple_size_v<Sndr>-2>; // exposition only
        +
        +  template<class Sndr, class Rcvr>
        +  using inner-ops-tuple =   // exposition only
        +    cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr,
        +      indices-for<Sndr>>;
        +
        +  template<class Sndr, class Rcvr>
        +    requires well-formed<state-type, Sndr, Rcvr> &&
        +      well-formed<inner-ops-tuple, Sndr, Rcvr>
        +  struct basic-operation {  // exposition only
        +    using operation_state_concept = operation_state_t;
        +    using tag-type = tag_of_t<Sndr>; // exposition only
        +
        +    Rcvr rcvr; // exposition only
        +    state-type<Sndr, Rcvr> state; // exposition only
        +    inner-ops-tuple<Sndr, Rcvr> inner-ops; // exposition only
        +
        +    basic-operation(Sndr&& sndr, Rcvr rcvr_init)  // exposition only
        +      : rcvr(std::move(rcvr_init))
        +      , state(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr))
        +      , inner-ops(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
        +    {}
        +
        +    void start() & noexcept {
        +      auto& [...ops] = inner-ops;
        +      impls-for<tag-type>::start(state, rcvr, ops...);
        +    }
        +  };
        +
        +  template<class Sndr, class Env>
        +  using completion-signatures-for =  see below; // exposition only
        +
        +  template<class Tag, class Data, class... Child>
        +  struct basic-sender {  // exposition only
        +    using sender_concept = sender_t;
        +
        +    decltype(auto) get_env() const noexcept {
        +      return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
        +    }
        +
        +    template<decays-to<basic-sender> Self, receiver Rcvr>
        +    auto connect(this Self&& self, Rcvr rcvr) -> basic-operation<Self, Rcvr> {
        +      return {std::forward<Self>(self), std::move(rcvr)};
        +    }
        +
        +    template<decays-to<basic-sender> Self, class Env>
        +    auto get_completion_signatures(this Self&& self, Env&& env) noexcept
        +      -> completion-signatures-for<Self, Env> {
        +      return {};
        +    }
        +
        +    Tag tag;            // exposition only
        +    Data data;          // exposition only
        +    Child0 child0;      // exposition only
        +    Child1 child1;      // exposition only
        +      ...
        +    Childn-1 childn-1;   // exposition only
        +  };
        +
        +  template <class Sndr>
        +  using data-type = decltype((declval<Sndr>().data)); // exposition only
        +
        +  template <class Sndr, size_t N = 0>
        +  using child-type = decltype((declval<Sndr>().childN)); // exposition only
        +}
        +
        +
      2. +

        Remarks: The default template argument for the Data template parameter +denotes an unspecified empty trivial class type.

        +
      3. +

        It is unspecified whether instances of basic-sender can be +aggregate initialized.

        +
      4. +

        An expression of type basic-sender is usable as the initializer of a +structured binding declaration [dcl.struct.bind].

        +
      5. +

        The member default-impls::get-attrs is +initialized with a callable object equivalent to the following +lambda:

        +
        [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
        +  if constexpr (sizeof...(child) == 1)
        +    return FWD-ENV(get_env(child...));
        +  else
        +    return empty_env();
        +}
        +
        +
      6. +

        The member default-impls::get-env is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept
        +  -> decltype(FWD-ENV(get_env(rcvr))) {
        +  return FWD-ENV(get_env(rcvr));
        +}
        +
        +
      7. +

        The member default-impls::get-state is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept -> decltype(auto) {
        +  return get<1>(std::forward<Sndr>(sndr));
        +}
        +
        +
      8. +

        The member default-impls::start is initialized +with a callable object equivalent to the following lambda:

        +
        [](auto& state, auto& rcvr, auto&... ops) noexcept -> void {
        +  (execution::start(ops), ...);
        +}
        +
        +
      9. +

        The member default-impls::complete is initialized +with a callable object equivalent to the following lambda:

        +
        []<class Index, class Rcvr, class Tag, class... Args>(
        +  Index, auto& state, Rcvr& rcvr, Tag, Args&&... args) noexcept
        +    -> void requires callable<Tag, Rcvr, Args...> {
        +  // Mandates: Index::value == 0
        +  Tag()(std::move(rcvr), std::forward<Args>(args)...);
        +}
        +
        +
      10. +

        For a subexpression sndr let Sndr be decltype((sndr)). Let rcvr be a receiver that has an associated environment of type Env such that sender_in<Sndr, Env> is true. completion-signatures-for<Sndr, Env> denotes +a specialization of completion_signatures, the set of whose +template arguments correspond to the set of completion operations +that are potentially evaluated as a result of calling start on the +operation state that results from connecting sndr and rcvr. When sender_in<Sndr, Env> is false, the type denoted by completion-signatures-for<Sndr, Env>, if any, +is not a specialization of completion_signatures.

        +

        Recommended practice: When sender_in<Sndr, Env> is false, +implementations are encouraged to use the type denoted by completion-signatures-for<Sndr, Env> to +communicate to users why.

        +
      +
    +
+

34.9.2. Sender concepts [exec.snd.concepts]

+
    +
  1. +

    The sender concept defines the requirements for a sender type +([async.ops]). The sender_in concept defines the requirements for a sender +type that can create asynchronous operations given an associated environment +type. The sender_to concept defines the requirements for a sender type +that can connect with a specific receiver type. The get_env customization +point object is used to access a sender’s associated attributes. The connect customization point object is used to connect ([async.ops]) a +sender and a receiver to produce an operation state.

    +
    namespace std::execution {
    +  template<class Sigs>
    +    concept valid-completion-signatures = see below; // exposition only
    +
    +  template<class Sndr>
    +    concept is-sender = // exposition only
    +      requires {
    +        requires derived_from<typename Sndr::sender_concept, sender_t>;
    +      };
    +
    +  template<class Sndr>
    +    concept enable-sender = // exposition only
    +      is-sender<Sndr> ||
    +      is-awaitable<Sndr, env-promise<empty_env>>;  // [exec.awaitables]
    +
    +  template<class Sndr>
    +    concept sender =
    +      bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint
    +      requires (const remove_cvref_t<Sndr>& sndr) {
    +        { get_env(sndr) } -> queryable;
    +      } &&
    +      move_constructible<remove_cvref_t<Sndr>> &&  // rvalues are movable, and
    +      constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable
    +
    +  template<class Sndr, class Env = empty_env>
    +    concept sender_in =
    +      sender<Sndr> &&
    +      queryable<Env> &&
    +      requires (Sndr&& sndr, Env&& env) {
    +        { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) }
    +          -> valid-completion-signatures;
    +      };
    +
    +  template<class Sndr, class Rcvr>
    +    concept sender_to =
    +      sender_in<Sndr, env_of_t<Rcvr>> &&
    +      receiver_of<Rcvr, completion_signatures_of_t<Sndr, env_of_t<Rcvr>>> &&
    +      requires (Sndr&& sndr, Rcvr&& rcvr) {
    +        connect(std::forward<Sndr>(sndr), std::forward<Rcvr>(rcvr));
    +      };
    +}
    +
    +
  2. +

    Given a subexpression sndr, let Sndr be decltype((sndr)), let Env be +the type of an environment, and let rcvr be a receiver with an associated +environment Env. A completion operation is a permissible completion for Sndr and Env if its +completion signature appears in the argument list of the specialization of completion_signatures denoted by completion_signatures_of_t<Sndr, Env>. Sndr and Env model sender_in<Sndr, Env> if all the completion +operations that are potentially evaluated by connecting sndr to rcvr and +starting the resulting operation state are permissible completions for Sndr and Env.

    +
  3. +

    A type Sigs satisfies and models the exposition-only concept valid-completion-signatures if it denotes a specialization +of the completion_signatures class template.

    +
  4. +

    The exposition-only concepts sender-of and sender-of-in define the requirements for a sender +type that completes with a given unique set of value result types.

    +
    namespace std::execution {
    +  template<class... As>
    +    using value-signature = set_value_t(As...); // exposition only
    +
    +  template<class Sndr, class Env, class... Values>
    +    concept sender-of-in =
    +      sender_in<Sndr, Env> &&
    +      MATCHING-SIG( // see [exec.general]
    +        set_value_t(Values...),
    +        value_types_of_t<Sndr, Env, value-signature, type_identity_t>);
    +
    +  template<class Sndr, class... Values>
    +    concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
    +}
    +
    +
  5. +

    Let sndr be an expression such that decltype((sndr)) is Sndr. The type tag_of_t<Sndr> is as follows:

    +
      +
    • +

      If the declaration auto&& [tag, data, ...children] = sndr; would be +well-formed, tag_of_t<Sndr> is an alias for decltype(auto(tag)).

      +
    • +

      Otherwise, tag_of_t<Sndr> is ill-formed.

      +
    +

    There is no way in standard C++ to determine whether the above declaration +is well-formed without causing a hard error, so this presumes compiler +magic. However, the author anticipates the adoption of [@P2141R1], which +makes it possible to implement this purely in the library. P2141 has already +been approved by EWG for C++26.

    +
  6. +

    Let sender-for be an exposition-only concept defined as follows:

    +
    namespace std::execution {
    +  template<class Sndr, class Tag>
    +  concept sender-for =
    +    sender<Sndr> &&
    +    same_as<tag_of_t<Sndr>, Tag>;
    +}
    +
    +
  7. +

    For a type T, SET-VALUE-SIG(T) denotes the type set_value_t() if T is cv void; otherwise, it denotes the type set_value_t(T).

    +
  8. +

    Library-provided sender types:

    +
      +
    • +

      Always expose an overload of a member connect that accepts an rvalue + sender.

      +
    • +

      Only expose an overload of a member connect that accepts an lvalue + sender if they model copy_constructible.

      +
    • +

      Model copy_constructible if they satisfy copy_constructible.

      +
    +
+

34.9.3. Awaitable helpers [exec.awaitables]

+
    +
  1. +

    The sender concepts recognize awaitables as senders. For this clause +([exec]), an awaitable is an expression that would be +well-formed as the operand of a co_await expression within a given +context.

    +
  2. +

    For a subexpression c, let GET-AWAITER(c, p) be +expression-equivalent to the series of transformations and conversions +applied to c as the operand of an await-expression in a coroutine, +resulting in lvalue e as described by [expr.await]/3.2-4, where p is an lvalue referring to the coroutine’s promise type, Promise. This includes the invocation of the promise type’s await_transform member if any, the invocation of the operator co_await picked by overload resolution if any, and any necessary implicit +conversions and materializations.

    +

    I have opened cwg#250 to give these +transformations a term-of-art so we can more easily refer to it here.

    +
  3. +

    Let is-awaitable be the following exposition-only +concept:

    +
    namespace std {
    +  template<class T>
    +  concept await-suspend-result = see below;
    +
    +  template<class A, class Promise>
    +  concept is-awaiter = // exposition only
    +    requires (A& a, coroutine_handle<Promise> h) {
    +      a.await_ready() ? 1 : 0;
    +      { a.await_suspend(h) } -> await-suspend-result;
    +      a.await_resume();
    +    };
    +
    +  template<class C, class Promise>
    +  concept is-awaitable =
    +    requires (C (*fc)() noexcept, Promise& p) {
    +      { GET-AWAITER(fc(), p) } -> is-awaiter<Promise>;
    +    };
    +}
    +
    +

    await-suspend-result<T> is true if and only if one + of the following is true:

    +
      +
    • +

      T is void, or

      +
    • +

      T is bool, or

      +
    • +

      T is a specialization of coroutine_handle.

      +
    +
  4. +

    For a subexpression c such that decltype((c)) is type C, and +an lvalue p of type Promise, await-result-type<C, Promise> denotes the type decltype(GET-AWAITER(c, p).await_resume()).

    +
  5. +

    Let with-await-transform be the exposition-only class template:

    +
    namespace std::execution {
    +  template<class T, class Promise>
    +    concept has-as-awaitable = // exposition only
    +      requires (T&& t, Promise& p) {
    +        { std::forward<T>(t).as_awaitable(p) } -> is-awaitable<Promise&>;
    +      };
    +
    +  template<class Derived>
    +    struct with-await-transform {
    +      template<class T>
    +        T&& await_transform(T&& value) noexcept {
    +          return std::forward<T>(value);
    +        }
    +
    +      template<has-as-awaitable<Derived> T>
    +        auto await_transform(T&& value)
    +          noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>())))
    +          -> decltype(std::forward<T>(value).as_awaitable(declval<Derived&>())) {
    +          return std::forward<T>(value).as_awaitable(static_cast<Derived&>(*this));
    +        }
    +    };
    +}
    +
    +
  6. +

    Let env-promise be the exposition-only class template:

    +
    namespace std::execution {
    +  template<class Env>
    +  struct env-promise : with-await-transform<env-promise<Env>> {
    +    unspecified get_return_object() noexcept;
    +    unspecified initial_suspend() noexcept;
    +    unspecified final_suspend() noexcept;
    +    void unhandled_exception() noexcept;
    +    void return_void() noexcept;
    +    coroutine_handle<> unhandled_stopped() noexcept;
    +
    +    const Env& get_env() const noexcept;
    +  };
    +}
    +
    +

    Specializations of env-promise are only used for the purpose of type computation; its members need not be + defined.

    +
+

34.9.4. execution::default_domain [exec.domain.default]

+
namespace std::execution {
+  struct default_domain {
+    template <sender Sndr, queryable... Env>
+        requires (sizeof...(Env) <= 1)
+      static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
+        noexcept(see below);
+
+    template <sender Sndr, queryable Env>
+      static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+
+    template<class Tag, sender Sndr, class... Args>
+      static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
+        noexcept(see below);
+  };
+}
+
+
34.9.4.1. Static members [exec.domain.default.statics]
+
template <sender Sndr, queryable... Env>
+    requires (sizeof...(Env) <= 1)
+  constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
+    noexcept(see below);
+
+
    +
  1. +

    Let e be the expression tag_of_t<Sndr>().transform_sender(std::forward<Sndr>(sndr), env...) if that +expression is well-formed; otherwise, std::forward<Sndr>(sndr).

    +
  2. +

    Returns: e.

    +
  3. +

    Remarks: The exception specification is equivalent to noexcept(e).

    +
+
template <sender Sndr, queryable Env>
+  constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+
+
    +
  1. +

    Let e be the expression tag_of_t<Sndr>().transform_env(std::forward<Sndr>(sndr), std::forward<Env>(env)) if that expression is well-formed; otherwise, static_cast<Env>(std::forward<Env>(env)).

    +
  2. +

    Mandates: noexcept(e) is true.

    +
  3. +

    Returns: e.

    +
+
template<class Tag, sender Sndr, class... Args>
+  constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
+    noexcept(see below);
+
+
    +
  1. +

    Let e be the expression Tag().apply_sender(std::forward<Sndr>(sndr), std::forward<Args>(args)...).

    +
  2. +

    Constraints: e is a well-formed expression.

    +
  3. +

    Returns: e.

    +
  4. +

    Remarks: The exception specification is equivalent to noexcept(e).

    +
+

34.9.5. execution::transform_sender [exec.snd.transform]

+
namespace std::execution {
+  template<class Domain, sender Sndr, queryable... Env>
+      requires (sizeof...(Env) <= 1)
+    constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env)
+      noexcept(see below);
+}
+
+
    +
  1. +

    Let transformed-sndr be the expression dom.transform_sender(std::forward<Sndr>(sndr), env...) if that expression +is well-formed; otherwise, default_domain().transform_sender(std::forward<Sndr>(sndr), env...). Let final-sndr be the expression transformed-sndr if transformed-sndr and sndr have the same type ignoring cv qualifiers; otherwise, it is the +expression transform_sender(dom, transformed-sndr, env...).

    +
  2. +

    Returns: final-sndr.

    +
  3. +

    Remarks: The exception specification is equivalent to noexcept(final-sndr).

    +
+

34.9.6. execution::transform_env [exec.snd.transform.env]

+
namespace std::execution {
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+}
+
+
    +
  1. +

    Let e be the expression dom.transform_env(std::forward<Sndr>(sndr), std::forward<Env>(env)) if +that expression is well-formed; otherwise, default_domain().transform_env(std::forward<Sndr>(sndr), std::forward<Env>(env)).

    +
  2. +

    Mandates: noexcept(e) is true.

    +
  3. +

    Returns: e.

    +
+

34.9.7. execution::apply_sender [exec.snd.apply]

+
namespace std::execution {
+  template<class Domain, class Tag, sender Sndr, class... Args>
+    constexpr decltype(auto) apply_sender(Domain dom, Tag, Sndr&& sndr, Args&&... args)
+      noexcept(see below);
+}
+
+
    +
  1. +

    Let e be the expression dom.apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...) if that expression + is well-formed; otherwise, default_domain().apply_sender(Tag(), std::forward<Sndr>(sndr), std::forward<Args>(args)...).

    +
  2. +

    Constraints: The expression e is well-formed.

    +
  3. +

    Returns: e.

    +
  4. +

    Remarks: The exception specification is equivalent to noexcept(e).

    +
+

34.9.8. execution::get_completion_signatures [exec.getcomplsigs]

+
    +
  1. +

    get_completion_signatures is a customization point object. Let sndr be an +expression such that decltype((sndr)) is Sndr, and let env be an +expression such that decltype((env)) is Env. Then get_completion_signatures(sndr, env) is expression-equivalent to:

    +
      +
    1. +

      decltype(sndr.get_completion_signatures(env)){} if that +expression is well-formed,

      +
    2. +

      Otherwise, remove_cvref_t<Sndr>::completion_signatures{} if that expression is well-formed,

      +
    3. +

      Otherwise, if is-awaitable<Sndr, env-promise<Env>> is true, then:

      +
      completion_signatures<
      +  SET-VALUE-SIG(await-result-type<Sndr,
      +                env-promise<Env>>), // see [exec.snd.concepts]
      +  set_error_t(exception_ptr),
      +  set_stopped_t()>{}
      +
      +
    4. +

      Otherwise, get_completion_signatures(sndr, env) is ill-formed.

      +
    +
  2. +

    Let rcvr be an rvalue receiver of type Rcvr, and let Sndr be the type of a +sender such that sender_in<Sndr, env_of_t<Rcvr>> is true. Let Sigs... be the +template arguments of the completion_signatures specialization named by completion_signatures_of_t<Sndr, env_of_t<Rcvr>>. Let CSO be +a completion function. If sender Sndr or its operation state cause the +expression CSO(rcvr, args...) to be potentially evaluated +([basic.def.odr]) then there shall be a signature Sig in Sigs... such +that MATCHING-SIG(decayed-typeof<CSO>(decltype(args)...), Sig) is true ([exec.general]).

    +
+

34.9.9. execution::connect [exec.connect]

+
    +
  1. +

    connect connects ([async.ops]) a sender with a receiver.

    +
  2. +

    The name connect denotes a customization point object. For subexpressions sndr and rcvr, let Sndr be decltype((sndr)) and Rcvr be decltype((rcvr)), and let DS and DR be the decayed types of Sndr and Rcvr, respectively.

    +
  3. +

    Let connect-awaitable-promise be the following class:

    +
    namespace std::execution {
    +  struct connect-awaitable-promise
    +    : with-await-transform<connect-awaitable-promise> {
    +    DR& rcvr; // exposition only
    +
    +    connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
    +
    +    suspend_always initial_suspend() noexcept { return {}; }
    +    [[noreturn]] suspend_always final_suspend() noexcept { terminate(); }
    +    [[noreturn]] void unhandled_exception() noexcept { terminate(); }
    +    [[noreturn]] void return_void() noexcept { terminate(); }
    +
    +    coroutine_handle<> unhandled_stopped() noexcept {
    +      set_stopped((DR&&) rcvr);
    +      return noop_coroutine();
    +    }
    +
    +    operation-state-task get_return_object() noexcept {
    +      return operation-state-task{
    +        coroutine_handle<connect-awaitable-promise>::from_promise(*this)};
    +    }
    +
    +    env_of_t<const DR&> get_env() const noexcept {
    +      return execution::get_env(rcvr);
    +    }
    +  };
    +}
    +
    +
  4. +

    Let operation-state-task be the following class:

    +
    namespace std::execution {
    +  struct operation-state-task {
    +    using operation_state_concept = operation_state_t;
    +    using promise_type = connect-awaitable-promise;
    +    coroutine_handle<> coro; // exposition only
    +
    +    explicit operation-state-task(coroutine_handle<> h) noexcept : coro(h) {}
    +    operation-state-task(operation-state-task&& o) noexcept
    +      : coro(exchange(o.coro, {})) {}
    +    ~operation-state-task() { if (coro) coro.destroy(); }
    +
    +    void start() & noexcept {
    +      coro.resume();
    +    }
    +  };
    +}
    +
    +
  5. +

    Let V name the type await-result-type<DS, connect-awaitable-promise>, let Sigs name the type:

    +
    completion_signatures<
    +  SET-VALUE-SIG(V), // see [exec.snd.concepts]
    +  set_error_t(exception_ptr),
    +  set_stopped_t()>
    +
    +

    and let connect-awaitable be an exposition-only +coroutine defined as follows:

    +
    namespace std::execution {
    +  template<class Fun, class... Ts>
    +  auto suspend-complete(Fun fun, Ts&&... as) noexcept { // exposition only
    +    auto fn = [&, fun]() noexcept { fun(std::forward<Ts>(as)...); };
    +
    +    struct awaiter {
    +      decltype(fn) fn;
    +
    +      static constexpr bool await_ready() noexcept { return false; }
    +      void await_suspend(coroutine_handle<>) noexcept { fn(); }
    +      [[noreturn]] void await_resume() noexcept { unreachable(); }
    +    };
    +    return awaiter{fn};
    +  };
    +
    +  operation-state-task connect-awaitable(DS sndr, DR rcvr) requires receiver_of<DR, Sigs> {
    +    exception_ptr ep;
    +    try {
    +      if constexpr (same_as<V, void>) {
    +        co_await std::move(sndr);
    +        co_await suspend-complete(set_value, std::move(rcvr));
    +      } else {
    +        co_await suspend-complete(set_value, std::move(rcvr), co_await std::move(sndr));
    +      }
    +    } catch(...) {
    +      ep = current_exception();
    +    }
    +    co_await suspend-complete(set_error, std::move(rcvr), std::move(ep));
    +  }
    +}
    +
    +
  6. +

    If Sndr does not satisfy sender or if Rcvr does not satisfy receiver, connect(sndr, rcvr) is ill-formed. Otherwise, the expression connect(sndr, rcvr) is +expression-equivalent to:

    +
      +
    1. +

      sndr.connect(rcvr) if that expression is well-formed.

      +
        +
      • +

        Mandates: The type of the expression above satisfies operation_state.

        +
      +
    2. +

      Otherwise, connect-awaitable(sndr, rcvr) if that expression is +well-formed.

      +
    3. +

      Otherwise, connect(sndr, rcvr) is ill-formed.

      +
    +
+

34.9.10. Sender factories [exec.factories]

+
34.9.10.1. execution::schedule [exec.schedule]
+
    +
  1. +

    schedule obtains a schedule-sender ([async.ops]) from a scheduler.

    +
  2. +

    The name schedule denotes a customization point object. For a +subexpression sch, the expression schedule(sch) is expression-equivalent to:

    +
      +
    1. +

      sch.schedule() if that expression is valid. If sch.schedule() does +not return a sender whose set_value completion scheduler is equal +to sch, the behavior of calling schedule(sch) is undefined.

      +
        +
      • +

        Mandates: The type of sch.schedule() satisfies sender.

        +
      +
    2. +

      Otherwise, schedule(sch) is ill-formed.

      +
    +
+
34.9.10.2. execution::just, execution::just_error, execution::just_stopped [exec.just]
+
    +
  1. +

    just, just_error, and just_stopped are sender factories whose +asynchronous operations complete synchronously in their start operation +with a value completion operation, an error completion operation, or a +stopped completion operation respectively.

    +
  2. +

    The names just, just_error, and just_stopped denote customization +point objects. Let just-cpo be one of just, just_error, or just_stopped. For a pack of subexpressions ts, let Ts be the template parameter pack decltype((ts)). The expression just-cpo(ts...) is ill-formed if:

    +
      +
    • +

      (movable-value<Ts> &&...) is false, or

      +
    • +

      just-cpo is just_error and sizeof...(ts) == 1 is false, or

      +
    • +

      just-cpo is just_stopped and sizeof...(ts) == 0 is false;

      +
    +

    Otherwise, it is expression-equivalent to make-sender(just-cpo, product-type{vs...}).

    +
  3. +

    For just, just_error, and just_stopped, let set-cpo be set_value, set_error, and set_stopped respectively. The +exposition-only class template impls-for ([exec.snd.general]) is specialized for just-cpo as +follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<decayed-typeof<just-cpo>> : default-impls {
    +    static constexpr auto start =
    +      [](auto& state, auto& rcvr) noexcept -> void {
    +        auto& [...ts] = state;
    +        set-cpo(std::move(rcvr), std::move(ts)...);
    +      };
    +  };
    +}
    +
    +
+
34.9.10.3. execution::read [exec.read]
+
    +
  1. +

    read is a sender factory for a sender whose asynchronous operation +completes synchronously in its start operation with a value completion +result equal to a value read from the receiver’s associated environment.

    +
  2. +

    read is a customization point object. For some query object q, +the expression read(q) is expression-equivalent to make-sender(read, q).

    +
  3. +

    The exposition-only class template impls-for ([exec.snd.general]) +is specialized for read as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<decayed-typeof<read>> : default-impls {
    +    static constexpr auto start =
    +      [](auto query, auto& rcvr) noexcept -> void {
    +        TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr)));
    +      };
    +  };
    +}
    +
    +
+

34.9.11. Sender adaptors [exec.adapt]

+
34.9.11.1. General [exec.adapt.general]
+
    +
  1. +

    Subclause [exec.adapt] specifies a set of sender adaptors.

    +
  2. +

    The bitwise OR operator is overloaded for the purpose of creating sender +chains. The adaptors also support function call syntax with equivalent +semantics.

    +
  3. +

    Unless otherwise specified, a sender adaptor is prohibited from causing +observable effects, apart from moving and copying its arguments, before the +returned sender is connected with a receiver using connect, and start is +called on the resulting operation state. This requirement applies to any +function that is selected by the implementation of the sender adaptor.

    +
  4. +

    Unless otherwise specified, a parent sender ([async.ops]) with a single child +sender sndr has an associated attribute object equal to FWD-ENV(get_env(sndr)) ([exec.fwd.env]). Unless +otherwise specified, a parent sender with more than one child senders has an +associated attributes object equal to empty_env{}. These +requirements apply to any function that is selected by the implementation of +the sender adaptor.

    +
  5. +

    Unless otherwise specified, when a parent sender is connected to a receiver rcvr, any receiver used to connect a child sender has an associated +environment equal to FWD-ENV(get_env(rcvr)). This +requirement applies to any sender returned from a function that is selected +by the implementation of such sender adaptor.

    +
  6. +

    If a sender returned from a sender adaptor specified in this subclause is +specified to include set_error_t(Err) among its set of completion signatures +where decay_t<Err> denotes the type exception_ptr, but the implementation +does not potentially evaluate an error completion operation with an exception_ptr argument, the implementation is allowed to omit the exception_ptr error completion signature from the set.

    +
+
34.9.11.2. Sender adaptor closure objects [exec.adapt.objects]
+
    +
  1. +

    A pipeable sender adaptor closure object is a function object that +accepts one or more sender arguments and returns a sender. For a sender +adaptor closure object c and an expression sndr such that decltype((sndr)) models sender, the following expressions are equivalent +and yield a sender:

    +
    c(sndr)
    +sndr | c
    +
    +

    Given an additional pipeable sender adaptor closure object d, the +expression c | d produces another pipeable sender adaptor closure object e:

    +

    e is a perfect forwarding call wrapper ([func.require]) with the following +properties:

    +
      +
    • +

      Its target object is an object d2 of type decay_t<decltype((d))> direct-non-list-initialized with d.

      +
    • +

      It has one bound argument entity, an object c2 of type decay_t<decltype((c))> direct-non-list-initialized with C.

      +
    • +

      Its call pattern is d2(c2(arg)), where arg is the argument used in a +function call expression of e.

      +
    +
+

The expression c | d is well-formed if and only if the initializations of + the state entities of e are all well-formed.

+
    +
  1. +

    An object t of type T is a pipeable sender adaptor closure object if T models derived_from<sender_adaptor_closure<T>>, T has no other base +classes of type sender_adaptor_closure<U> for any other type U, and T does not model sender.

    +
  2. +

    The template parameter D for sender_adaptor_closure can be an incomplete +type. Before any expression of type cv D appears as an +operand to the | operator, D shall be complete and model derived_from<sender_adaptor_closure<D>>. The behavior of an expression +involving an object of type cv D as an operand to the | operator is undefined if overload resolution selects a program-defined operator| function.

    +
  3. +

    A pipeable sender adaptor object is a customization point object that +accepts a sender as its first argument and returns a sender.

    +
  4. +

    If a pipeable sender adaptor object accepts only one argument, then it is a +pipeable sender adaptor closure object.

    +
  5. +

    If a pipeable sender adaptor object adaptor accepts more than one argument, +then let sndr be an expression such that decltype((sndr)) models sender, let args... be arguments such that adaptor(sndr, args...) is a +well-formed expression as specified in the rest of this subclause +([exec.adapt.objects]), and let BoundArgs be a pack that denotes decay_t<decltype((args))>.... The expression adaptor(args...) produces a +pipeable sender adaptor closure object f that is a perfect forwarding call +wrapper with the following properties:

    +
      +
    • +

      Its target object is a copy of adaptor.

      +
    • +

      Its bound argument entities bound_args consist of objects of types BoundArgs... direct-non-list-initialized with std::forward<decltype((args))>(args)..., respectively.

      +
    • +

      Its call pattern is adaptor(rcvr, bound_args...), where rcvr is the +argument used in a function call expression of f.

      +
    +

    The expression adaptor(args...) is well-formed if and only if the +initializations of the bound argument entities of the result, as specified +above, are all well-formed.

    +
+
34.9.11.3. execution::on [exec.on]
+
    +
  1. +

    on adapts an input sender into a sender that will start on an execution +agent belonging to a particular scheduler’s associated execution resource.

    +
  2. +

    The name on denotes a customization point object. For some subexpressions sch and sndr, if decltype((sch)) does not satisfy scheduler, or decltype((sndr)) does not satisfy sender, on(sch, sndr) is ill-formed.

    +
  3. +

    Otherwise, the expression on(sch, sndr) is expression-equivalent to:

    +
    transform_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  make-sender(on, sch, sndr));
    +
    +
  4. +

    Let out_sndr and env be subexpressions such that OutSndr is decltype((out_sndr)). If sender-for<OutSndr, on_t> is false, then the expressions on.transform_env(out_sndr, env) and on.transform_sender(out_sndr, env) are ill-formed; +otherwise:

    +
      +
    • +

      on.transform_env(out_sndr, env) is equivalent to:

      +
      auto&& [ign1, sch, ign2] = out_sndr;
      +return JOIN-ENV(SCHED-ENV(sch), FWD-ENV(env));
      +
      +
    • +

      on.transform_sender(out_sndr, env) is equivalent to:

      +
      auto&& [ign, sch, sndr] = out_sndr;
      +return let_value(
      +  schedule(sch),
      +  [sndr = std::forward_like<OutSndr>(sndr)]() mutable {
      +    return std::move(sndr);
      +  });
      +
      +
    +
  5. +

    Let out_sndr be a subexpression denoting a sender returned from on(sch, sndr) or one equal to such, and let OutSndr be the type decltype((out_sndr)). Let out_rcvr be a subexpression denoting a receiver that has an environment of +type Env such that sender_in<OutSndr, Env> is true. Let op be an lvalue +referring to the operation state that results from connecting out_sndr with out_rcvr. Calling start(op) shall start sndr on an execution agent of the +associated execution resource of sch, or failing that, shall execute an +error completion on out_rcvr.

    +
+
34.9.11.4. execution::transfer [exec.transfer]
+
    +
  1. +

    transfer adapts a sender into one with a different associated set_value completion scheduler. It results in a transition +between different execution resources when executed.

    +
  2. +

    The name transfer denotes a customization point object. For some +subexpressions sch and sndr, if decltype((sch)) does not satisfy scheduler, or decltype((sndr)) does not satisfy sender, transfer(sndr, sch) is ill-formed.

    +
  3. +

    Otherwise, the expression transfer(sndr, sch) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(transfer, sch, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for is specialized +for transfer_t as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<transfer_t> : default-impls {
    +    static constexpr auto get_attrs =
    +      [](const auto& data, const auto& child) noexcept -> decltype(auto) {
    +        return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
    +      };
    +  };
    +}
    +
    +
  5. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)). If sender-for<Sndr, transfer_t> is false, then the expression transfer.transform_sender(sndr, env) is ill-formed; otherwise, it +is equal to:

    +
    auto [tag, data, child] = sndr;
    +return schedule_from(std::move(data), std::move(child));
    +
    +

    This causes the transfer(sndr, sch) sender to become schedule_from(sch, sndr) when it is connected with a receiver with an +execution domain that does not customize transfer.

    +
  6. +

    Let out_sndr be a subexpression denoting a sender returned from transfer(sndr, sch) or one equal to such, and let OutSndr be the type decltype((out_sndr)). Let out_rcvr be a subexpression denoting a +receiver that has an environment of type Env such that sender_in<OutSndr, Env> is true. Let op be an lvalue referring to the operation state that +results from connecting out_sndr with out_rcvr. Calling start(op) shall start sndr on the current execution agent and execute completion +operations on out_rcvr on an execution agent of the execution resource +associated with sch. If scheduling onto sch fails, execute an error +completion on out_rcvr on an unspecified execution agent.

    +
+
34.9.11.5. execution::schedule_from [exec.schedule.from]
+
    +
  1. +

    schedule_from schedules work dependent on the completion of a sender onto a +scheduler’s associated execution resource. schedule_from is not meant to be used in user code; it is +used in the implementation of transfer.

    +
  2. +

    The name schedule_from denotes a customization point object. For some +subexpressions sch and sndr, let Sch be decltype((sch)) and Sndr be decltype((sndr)). If Sch does not satisfy scheduler, or Sndr does not +satisfy sender, schedule_from is ill-formed.

    +
  3. +

    Otherwise, the expression schedule_from(sch, sndr) is expression-equivalent +to:

    +
    transform_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  make-sender(schedule_from, sch, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for schedule_from_t as +follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<schedule_from_t> : default-impls {
    +    static constexpr auto get-attrs = see below;
    +    static constexpr auto get-state = see below;
    +    static constexpr auto complete = see below;
    +  };
    +}
    +
    +
      +
    1. +

      The member impls-for<schedule_from_t>::get-attrs is initialized +with a callable object equivalent to the following lambda:

      +
      [](const auto& data, const auto& child) noexcept -> decltype(auto) {
      +  return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
      +}
      +
      +
    2. +

      The member impls-for<schedule_from_t>::get-state is initialized +with a callable object equivalent to the following lambda:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
      +    requires sender_in<child-type<Sndr>, env_of_t<Rcvr>> {
      +  return apply(
      +    [&]<class Sch, class Child>(auto, Sch sch, Child&& child) {
      +      using variant-type = see below;
      +      using receiver-type = see below;
      +      using operation-type = connect_result_t<schedule_result_t<Sch>, receiver-type>;
      +
      +      struct state-type {
      +        Rcvr& rcvr;
      +        variant-type async-result;
      +        operation-type op-state;
      +
      +        explicit state-type(Sch sch, Rcvr& rcvr)
      +          : rcvr(rcvr), op-state(connect(schedule(sch), receiver-type{{}, this})) {}
      +      };
      +
      +      return state-type{sch, rcvr};
      +    },
      +    std::forward<Sndr>(sndr));
      +}
      +
      +
        +
      1. +

        The local class state-type is a structural type.

        +
      2. +

        Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<Child, env_of_t<Rcvr>>. Let as-tuple be an alias template that transforms a + completion signature Tag(Args...) into the tuple specialization decayed-tuple<Tag, Args...>. + Then variant-type denotes the type variant<monostate, as-tuple<Sigs>...>, + except with duplicate types removed.

        +
      3. +

        Let receiver-type denote the following exposition-only + class:

        +
        namespace std::execution {
        +  struct receiver-type {
        +    using receiver_concept = receiver_t;
        +    state-type* state; // exposition only
        +
        +    Rcvr&& base() && noexcept { return std::move(state->rcvr); }
        +    const Rcvr& base() const & noexcept { return state->rcvr; }
        +
        +    void set_value() && noexcept {
        +      visit(
        +        [this]<class Tuple>(Tuple& result) noexcept -> void {
        +          if constexpr (!same_as<monostate, Tuple>) {
        +            auto& [tag, ...args] = result;
        +            tag(std::move(state->rcvr), std::move(args)...);
        +          }
        +        },
        +        state->async-result);
        +    }
        +
        +    template<class Error>
        +    void set_error(Error&& err) && noexcept {
        +      execution::set_error(std::move(state->rcvr), std::forward<Error>(err));
        +    }
        +
        +    void set_stopped() && noexcept {
        +      execution::set_stopped(std::move(state->rcvr));
        +    }
        +
        +    decltype(auto) get_env() const noexcept {
        +      return FWD-ENV(execution::get_env(state->rcvr));
        +    }
        +  };
        +}
        +
        +
      +
    3. +

      The member impls-for<schedule_from_t>::complete is initialized with a callable object equivalent to the following lambda:

      +
      []<class Tag, class... Args>(auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
      +  using result_t = decayed-tuple<Tag, Args...>;
      +  constexpr bool nothrow = is_nothrow_constructible_v<result_t, Tag, Args...>;
      +
      +  TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) {
      +    state.async-result.template emplace<result_t>(Tag(), std::forward<Args>(args)...);
      +  }());
      +
      +  if (state.async-result.valueless_by_exception())
      +    return;
      +  if (state.async-result.index() == 0)
      +    return;
      +
      +  start(state.op-state);
      +};
      +
      +
    +
  5. +

    Let the subexpression out_sndr denote the result of the invocation schedule_from(sch, sndr) or an object copied or moved from such, and let +the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an +asynchronous operation ([async.ops]) that, when started:

    +
      +
    • +

      eventually completes on an execution agent belonging to the associated +execution resource of sch, and

      +
    • +

      completes with the same async result as sndr.

      +
    +
+
34.9.11.6. execution::then, execution::upon_error, execution::upon_stopped [exec.then]
+
    +
  1. +

    then attaches an invocable as a continuation for an input sender’s value +completion operation. upon_error and upon_stopped do the same for the +error and stopped completion operations respectively, sending the result +of the invocable as a value completion.

    +
  2. +

    The names then, upon_error, and upon_stopped denote customization point +objects. Let the expression then-cpo be one of then, upon_error, or upon_stopped. For subexpressions sndr and f, let Sndr be decltype((sndr)) and let F be the decayed type of f. If Sndr does not +satisfy sender, or F does not satisfy movable-value, then-cpo(sndr, f) is ill-formed.

    +
  3. +

    Otherwise, the expression then-cpo(sndr, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(then-cpo, f, sndr));
    +
    +
  4. +

    For then, upon_error, and upon_stopped, let set-cpo be set_value, set_error, and set_stopped respectively. The +exposition-only class template impls-for ([exec.snd.general]) is specialized for then-cpo as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<decayed-typeof<then-cpo>> : default-impls {
    +    static constexpr auto complete =
    +      []<class Tag, class... Args>
    +        (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
    +          if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
    +            TRY-SET-VALUE(std::move(rcvr),
    +                          invoke(std::move(fn), std::forward<Args>(args)...));
    +          } else {
    +            Tag()(std::move(rcvr), std::forward<Args>(args)...);
    +          }
    +        };
    +  };
    +}
    +
    +
  5. +

    The expression then-cpo(sndr, f) has undefined behavior +unless it returns a sender out_sndr that:

    +
      +
    1. +

      Invokes f or a copy of such with the value, error, or stopped result +datums of sndr (for then, upon_error, and upon_stopped respectively), using the result value of f as out_sndr's value +completion, and

      +
    2. +

      Forwards all other completion operations unchanged.

      +
    +
+
34.9.11.7. execution::let_value, execution::let_error, execution::let_stopped, [exec.let]
+
    +
  1. +

    let_value, let_error, and let_stopped transform a sender’s value, +error, and stopped completions respectively into a new child asynchronous +operation by passing the sender’s result datums to a user-specified +callable, which returns a new sender that is connected and started.

    +
  2. +

    Let the expression let-cpo be one of let_value, let_error, or let_stopped and let set-cpo be the +completion function that corresponds to let-cpo (set_value for let_value, etc.). For a subexpression sndr, let let-env(sndr) be expression-equivalent to the first +well-formed expression below:

    +
      +
    • +

      SCHED-ENV(get_completion_scheduler<decayed-typeof<set-cpo>>(get_env(sndr)))

      +
    • +

      MAKE-ENV(get_domain, get_domain(get_env(sndr)))

      +
    • +

      empty_env{}

      +
    +
  3. +

    The names let_value, let_error, and let_stopped denote customization +point objects. For subexpressions sndr and f, let Sndr be decltype((sndr)), +let F be the decayed type of f. If Sndr does not satisfy sender or if F does not satisfy movable-value, the expression let-cpo(sndr, f) is ill-formed. If F does not satisfy invocable, the expression let_stopped(sndr, f) is ill-formed.

    +
  4. +

    Otherwise, the expression let-cpo(sndr, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(let-cpo, f, sndr));
    +
    +
  5. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for let-cpo as +follows:

    +
    namespace std::execution {
    +  template<class State, class Rcvr, class... Args>
    +  void let-bind(State& state, Rcvr& rcvr, Args&&... args); // exposition only
    +
    +  template<>
    +  struct impls-for<decayed-typeof<let-cpo>> : default-impls {
    +    static constexpr auto get-state = see below;
    +    static constexpr auto complete = see below;
    +  };
    +}
    +
    +
      +
    1. +

      Let receiver2 denote the following exposition-only class template:

      +
      namespace std::execution {
      +  template<class Rcvr, class Env>
      +  struct receiver2 : Rcvr {
      +    explicit receiver2(Rcvr rcvr, Env env)
      +      : Rcvr(std::move(rcvr)), env(std::move(env)) {}
      +
      +    auto get_env() const noexcept {
      +      const Rcvr& rcvr = *this;
      +      return JOIN-ENV(env, FWD-ENV(execution::get_env(rcvr)));
      +    }
      +
      +    Env env; // exposition only
      +  };
      +}
      +
      +
    2. +

      impls-for<decayed-typeof<let-cpo>>::get-state is +is initialized with a callable object equivalent to the following:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) requires see below {
      +  auto&& [tag, data, child] = std::forward<Sndr>(sndr);
      +  return [&]<class Fn, class Env>(Fn fn, Env env) {
      +    using args-variant-type = see below;
      +    using ops2-variant-type = see below;
      +
      +    struct state-type {
      +      Fn fn;
      +      Env env;
      +      args-variant-type args;
      +      ops2-variant-type ops2;
      +    };
      +    return state-type{std::move(fn), std::move(env), {}, {}};
      +  }(std::forward_like<Sndr>(data), let-env(child));
      +}
      +
      +
        +
      1. +

        Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<child-type<Sndr>, env_of_t<Rcvr>>. Let LetSigs be a pack of those types in Sigs with a return type of decayed-typeof<set-cpo>. Let as-tuple be an alias template such that as-tuple<Tag(Args...)> denotes the type decayed-tuple<Args...>. Then args-variant-type denotes the type variant<monostate, as-tuple<LetSigs>...>.

        +
      2. +

        Let as-sndr2 be an alias template such that as-sndr2<Tag(Args...)> denotes the type call-result-t<Fn, decay_t<Args>&...>. +Then ops2-variant-type denotes the type variant<monostate, connect_result_t<as-sndr2<LetSigs>, receiver2<Rcvr, Env>>...>.

        +
      3. +

        The requires-clause constraining the above lambda is +satisfied if and only if the types args-variant-type and ops2-variant-type are well-formed.

        +
      +
    3. +

      The exposition-only function template let-bind is equal to:

      +
      auto& args = state.args.emplace<decayed-tuple<Args...>>(std::forward<Args>(args)...);
      +auto sndr2 = apply(std::move(state.fn), args);
      +auto rcvr2 = receiver2{std::move(rcvr), std::move(state.env)};
      +auto mkop2 = [&] { return connect(std::move(sndr2), std::move(rcvr2)); };
      +auto& op2 = state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2});
      +start(op2);
      +
      +
    4. +

      impls-for<decayed-typeof<let-cpo>>::complete is +is initialized with a callable object equivalent to the following:

      +
      []<class Tag, class... Args>
      +  (auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void {
      +    if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
      +      TRY-EVAL(std::move(rcvr), let-bind(state, rcvr, std::forward<Args>(args)...));
      +    } else {
      +      Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +    }
      +  }
      +
      +
    +
  6. +

    Let sndr and env be subexpressions, and let Sndr be decltype((sndr)). +If sender-for<Sndr, decayed-typeof<let-cpo>> is false, then the expression let-cpo.transform_env(sndr, env) is ill-formed. Otherwise, it is equal to JOIN-ENV(let-env(sndr), FWD-ENV(env)).

    +
  7. +

    Let the subexpression out_sndr denote the result of the invocation let-cpo(sndr, f) or an object copied or moved from such, +and let the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an asynchronous operation +([async.ops]) that, when started:

    +
      +
    • +

      invokes f when set-cpo is called with sndr's + result datums,

      +
    • +

      makes its completion dependent on the completion of a sender returned + by f, and

      +
    • +

      propagates the other completion operations sent by sndr.

      +
    +
+
34.9.11.8. execution::bulk [exec.bulk]
+
    +
  1. +

    bulk runs a task repeatedly for every index in an index space.

    +
  2. +

    The name bulk denotes a customization point object. For subexpressions sndr, shape, and f, let Sndr be decltype((sndr)), let Shape be +the decayed type of shape, and let F be the decayed type of f. If Sndr does not satisfy sender, or if Shape does not satisfy integral, +or if F does not satisfy movable-value, bulk(sndr, shape, f) is ill-formed.

    +
  3. +

    Otherwise, the expression bulk(sndr, shape, f) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(bulk, product-type{shape, f}, sndr));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for bulk_t as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<bulk_t> : default-impls {
    +    static constexpr auto complete = see below;
    +  };
    +}
    +
    +
      +
    1. +

      The member impls-for<bulk_t>::complete is +initialized with a callable object equivalent to the following lambda:

      +
      []<class Index, class State, class Rcvr, class Tag, class... Args>
      +  (Index, State& state, Rcvr& rcvr, Tag, Args&&... args) noexcept -> void requires see below {
      +    if constexpr (same_as<Tag, set_value_t>) {
      +      auto& [shape, f] = state;
      +      constexpr bool nothrow = noexcept(f(auto(shape), args...));
      +      TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) {
      +        for (auto max = shape, i = 0; i < max; ++i) {
      +          f(auto(i), args...);
      +        }
      +        Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +      }());
      +    } else {
      +      Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +    }
      +  }
      +
      +
        +
      1. +

        The expression in the requires-clause of the lambda above is true if and only if Tag denotes a type other than set_value_t or if the expression f(auto(shape), args...) is well-formed.

        +
      +
    +
  5. +

    Let the subexpression out_sndr denote the result of the invocation bulk(sndr, shape, f) or an object copied or moved from such, +and let the subexpression rcvr denote a receiver such that the expression connect(out_sndr, rcvr) is well-formed. The expression connect(out_sndr, rcvr) has undefined behavior unless it creates an asynchronous operation +([async.ops]) that, when started:

    +
      +
    • +

      on a value completion operation, invokes f(i, args...) for every i of type Shape from 0 to shape, where args is a pack of lvalue + subexpressions referring to the value completion result datums of the + input sender, and

      +
    • +

      propagates all completion operations sent by sndr.

      +
    +
+
34.9.11.9. execution::split and execution::ensure_started [exec.split]
+
    +
  1. +

    split adapts an arbitrary sender into a sender that can be connected +multiple times. ensure_started eagerly starts the execution of a sender, +returning a sender that is usable as input to additional sender algorithms.

    +
  2. +

    Let shared-env be the type of an environment such that, +given an instance env, the expression get_stop_token(env) is well-formed +and has type inplace_stop_token.

    +
  3. +

    + The names split and ensure_started denote customization point objects. +Let the expression shared-cpo be one of split or ensure_started. For a subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, shared-env> + or constructible_from<decay_t<env_of_t<Sndr>>, env_of_t<Sndr>> + is false, shared-cpo(sndr) is ill-formed. +

    +

    Although it has not yet been approved by LEWG, there +is a bug in the current wording that makes it impossible to safely copy the +attributes of a sender; it may have reference semantics, leading to a +dangling reference. I am striking this part for now and will bring a fix to +LEWG.

    +
  4. +

    Otherwise, the expression shared-cpo(sndr) is +expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(shared-cpo, {}, sndr));
    +
    +
      +
    • +

      The default implementation of transform_sender will have the effect of connecting the sender to a receiver and, in the +case of ensure_started, calling start on the resulting operation +state. It will return a sender with a different tag type.

      +
    +
  5. +

    Let local-state denote the following exposition-only class:

    +
    namespace std::execution {
    +  struct local-state-base {
    +    virtual ~local-state-base() = default;
    +    virtual void notify() noexcept = 0;
    +    virtual void detach() noexcept = 0;
    +  };
    +
    +  template<class Sndr, class Rcvr>
    +  struct local-state : local-state-base {
    +    using on-stop-request = see below;
    +    using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>::
    +                                template callback_type<on-stop-request>;
    +
    +    local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
    +    ~local-state();
    +
    +    void notify() noexcept override;
    +    void detach() noexcept override;
    +
    +    optional<on-stop-callback> on_stop;
    +    shared-state<Sndr>* sh_state;
    +    Rcvr* rcvr;
    +  };
    +}
    +
    +
      +
    1. +
      local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
      +
        +
      1. +

        Effects: Equivalent to:

        +
        auto&& [tag, data, child] = std::forward<Sndr>(sndr);
        +this->sh_state = data.sh_state.get();
        +this->sh_state->inc-ref();
        +this->rcvr = &rcvr;
        +
        +
      +
    2. +
      ~local-state();
      +
        +
      1. +

        Effects: Equivalent to:

        +
        detach();
        +sh_state->dec-ref();
        +
        +
      +
    3. +
      void notify() noexcept override;
      +
        +
      1. +

        Effects: Equivalent to:

        +
        on_stop.reset();
        +visit(
        +  [this]<class Tuple>(Tuple&& tupl) noexcept -> void {
        +    apply(
        +      [this](auto tag, auto&... args) noexcept -> void {
        +        tag(std::move(*rcvr), std::forward_like<Tuple>(args)...);
        +      },
        +      tupl);
        +  },
        +  QUAL(sh_state->result));
        +);
        +
        +

        where QUAL is std::move if same_as<tag_of_t<Sndr>, ensure-started-impl-tag> is true, and as_const otherwise.

        +
      +
    4. +
      void detach() noexcept override;
      +
        +
      1. +

        Effects: Equivalent to sh_state->detach() if same_as<tag_of_t<Sndr>, ensure-started-impl-tag> is true; otherwise, +nothing.

        +
      +
    +
  6. +

    Let shared-receiver denote the following exposition-only class +template:

    +
    namespace std::execution {
    +  template<class Sndr>
    +  struct shared-receiver {
    +    using receiver_concept = receiver_t;
    +
    +    template<class Tag, class... Args>
    +    void complete(Tag, Args&&... args) noexcept { // exposition only
    +      try {
    +        using tuple_t = decayed-tuple<Tag, Args...>;
    +        sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
    +      } catch (...) {
    +        using tuple_t = tuple<set_error_t, exception_ptr>;
    +        sh_state->result.template emplace<tuple_t>(set_error, current_exception());
    +      }
    +      sh_state->notify();
    +    }
    +
    +    template<class... Args>
    +    void set_value(Args&&... args) && noexcept {
    +      complete(execution::set_value, std::forward<Args>(args)...);
    +    }
    +
    +    template<class Error>
    +    void set_error(Error&& err) && noexcept {
    +      complete(execution::set_error, std::forward<Error>(err));
    +    }
    +
    +    void set_stopped() && noexcept {
    +      complete(execution::set_stopped);
    +    }
    +
    +    struct env { // exposition only
    +      shared-state<Sndr>* sh-state; // exposition only
    +
    +      inplace_stop_source query(get_stop_token_t) const noexcept {
    +        return sh-state->stop_src.get_token();
    +      }
    +    };
    +
    +    env get_env() const noexcept {
    +      return env{sh_state};
    +    }
    +
    +    shared-state<Sndr>* sh_state;
    +  };
    +}
    +
    +
  7. +

    Let shared-state denote the following exposition-only class +template:

    +
    namespace std::execution {
    +  template<class Sndr>
    +  struct shared-state {
    +    using variant-type = see below;
    +    using state-list-type = see below;
    +    using state-flag-type = see below;
    +
    +    explicit shared-state(Sndr&& sndr);
    +
    +    void start-op() noexcept;
    +    void notify() noexcept;
    +    void detach() noexcept;
    +    void inc-ref() noexcept;
    +    void dec-ref() noexcept;
    +
    +    inplace_stop_source stop_src{};
    +    variant-type result{};
    +    state-list-type waiting_states;
    +    state-flag-type completed;
    +    atomic<size_t> ref_count{1};
    +    connect_result_t<Sndr, shared-receiver<Sndr>> op_state;
    +  };
    +}
    +
    +
      +
    1. +

      Let Sigs be a pack of the arguments to the completion_signatures specialization named by completion_signatures_of_t<Sndr>. Let as-tuple be an + alias template such that as-tuple<Tag(Args...)> denotes the type decayed-tuple<Tag, Args...>. Then variant-type denotes the type variant<tuple<set_stopped_t>, tuple<set_error_t, exception_ptr>, as-tuple<Sigs>...>, but with + duplicate types removed.

      +
    2. +

      Let state-list-type be a type that stores a list of pointers + to local-state-base objects and that permits atomic insertion. + Let state-flag-type be a type that can be atomically toggled + between true and false.

      +
    3. +
        explicit shared-state(Sndr&& sndr);
      +
        +
      1. +

        Effects: Initializes op_state with the result of connect(std::forward<Sndr>(sndr), shared-receiver{this}).

        +
      2. +

        Postcondition: waiting_states is empty, and completed is false.

        +
      +
    4. +
        void start-op() noexcept;
      +
        +
      1. +

        Effects: inc-ref(). If stop_src.stop_requested() is true, calls notify(); otherwise, calls start(op_state).

        +
      +
    5. +
        void notify() noexcept;
      +
        +
      1. +

        Effects: Atomically does the following:

        +
          +
        • +

          Sets completed to true, and

          +
        • +

          Exchanges waiting_states with an empty list, storing the old +value in a local prior_states. For each pointer p in prior_states, calls p->notify(). +Finally, calls dec-ref().

          +
        +
      +
    6. +
        void detach() noexcept;
      +
        +
      1. +

        Effects: If completed is false and waiting_states is empty, + calls stop_src.request_stop(). This has + the effect of requesting early termination of any asynchronous + operation that was started as a result of a call to ensure_started, + but only if the resulting sender was never connected and started.

        +
      +
    7. +
        void inc-ref() noexcept;
      +
        +
      1. +

        Effects: Increments ref_count.

        +
      +
    8. +
        void dec-ref() noexcept;
      +
        +
      1. +

        Effects: Decrements ref_count. If the new value of ref_count is 0, calls delete this.

        +
      2. +

        Synchronization: If dec_ref() does not decrement the ref_count to 0 then synchronizes with + the call to dec_ref() that decrements ref_count to 0.

        +
      +
    +
  8. +

    For each type split_t and ensure_started_t, there is a different, +associated exposition-only implementation tag type, split-impl-tag and ensure-started-impl-tag, respectively. Let shared-impl-tag be the associated implementation tag type of shared-cpo. Given an expression sndr, the expression shared-cpo.transform_sender(sndr) is equivalent to:

    +
    auto&& [tag, data, child] = sndr;
    +auto* sh_state = new shared-state{std::forward_like<decltype((sndr))>(child)};
    +return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
    +
    +

    where shared-wrapper is an exposition-only class that manages the +reference count of the shared-state object pointed to by sh_state. shared-wrapper models movable with move operations nulling out the +moved-from object. If tag is split_t, shared-wrapper models copyable with copy operations incrementing the reference count by calling sh_state->inc-ref(). The constructor calls sh_state->start-op() if tag is ensure_started_t. The +destructor has no effect if sh_state is null; otherwise, it calls sh_state->detach() if tag is ensure_started_t; +and finally, it decrements the reference count by calling sh_state->dec-ref().

    +
  9. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for shared-impl-tag as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<shared-impl-tag> : default-impls {
    +    static constexpr auto get-state = see below;
    +    static constexpr auto start = see below;
    +  };
    +}
    +
    +
      +
    1. +

      The member impls-for<shared-impl-tag>::get-state is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class Sndr>(Sndr&& sndr, auto& rcvr) noexcept {
      +  return local-state{std::forward<Sndr>(sndr), rcvr};
      +}
      +
      +
    2. +

      The member impls-for<shared-impl-tag>::start is initialized with a callable object that has a call operator +equivalent to the following:

      +
      template <class Sndr, class Rcvr>
      +void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
      +
      +
        +
      1. +

        Effects:

        +
          +
        1. +

          If state.sh_state->completed is true, calls state.notify() and returns.

          +
        2. +

          Otherwise, calls:

          +
          state.on_stop.emplace(
          +  get_stop_token(get_env(rcvr)),
          +  on-stop-request{state.sh_state->stop_src})
          +
          +

          If shared-impl-tag is ensure-started-impl-tag, and if state.sh_state->stop_src.stop_requested() is true, calls set_stopped(std::move(rcvr)) and returns.

          +
        3. +

          Then atomically does the following:

          +
            +
          • +

            Inserts &state into state.sh_state->waiting_states, and

            +
          • +

            Reads the value of state.sh_state->completed.

            +
          +

          If the value is true, calls state.notify() and returns.

          +
        4. +

          If shared-impl-tag is split-impl-tag, and if &state is the first item added to state.sh_state->waiting_states, calls state.sh_state->start-op().

          +
        +
      +
    +
  10. +
    + Under the following conditions, the results of the +child operation are discarded: +
      +
    • +

      When a sender returned from ensure_started is destroyed without being +connected to a receiver, or

      +
    • +

      If the sender is connected to a receiver but the operation state +is destroyed without having been started, or

      +
    • +

      If polling the receiver’s stop token indicates that stop has been +requested when start is called, and the operation has not yet +completed.

      +
    +
    +

    +
+
34.9.11.10. execution::when_all [exec.when.all]
+
    +
  1. +

    when_all and when_all_with_variant both adapt multiple input senders into +a sender that completes when all input senders have completed. when_all only accepts senders with a single value completion signature and on success +concatenates all the input senders' value result datums into its own value +completion operation. when_all_with_variant(sndrs...) is semantically +equivalent to when_all(into_variant(sndrs)...), where sndrs is a pack of +subexpressions of sender types.

    +
  2. +

    The names when_all and when_all_with_variant denote customization point +objects. For some subexpressions sndri..., let Sndri... be decltype((sndri)).... The expressions when_all(sndri...) and when_all_with_variant(sndri...) are ill-formed if +any of the following is true:

    +
      +
    • +

      If the number of subexpressions in sndri... is 0, or

      +
    • +

      If any type Sndri does not satisfy sender.

      +
    • +

      If the types of the expressions get-domain-early(sndri) do not share +a common type ([meta.trans.other]) for all values of i.

      +
    +

    Otherwise, let CD be the common type of the input senders' domains.

    +
  3. +

    The expression when_all(sndri...) is +expression-equivalent to:

    +
    transform_sender(
    +  CD(),
    +  make-sender(when_all, {}, sndr0, ... sndrn-1));
    +
    +
  4. +

    The exposition-only class template impls-for ([exec.snd.general]) is specialized for when_all_t as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<when_all_t> : default-impls {
    +    static constexpr auto get-attrs = see below;
    +    static constexpr auto get-env = see below;
    +    static constexpr auto get-state = see below;
    +    static constexpr auto start = see below;
    +    static constexpr auto complete = see below;
    +  };
    +}
    +
    +
      +
    1. +

      The member impls-for<when_all_t>::get-attrs is initialized with a callable object equivalent to the following lambda +expression:

      +
      [](auto&&, auto&&... child) noexcept {
      +  auto domain_fn = []<class... Ds>(Ds...) noexcept { return common_type_t<Ds...>(); };
      +  using domain_type = decltype(domain_fn(get-domain-early(child)...));
      +  if constexpr (same_as<domain_type, default_domain>) {
      +    return empty_env();
      +  } else {
      +    return MAKE-ENV(get_domain, domain_type());
      +  }
      +}
      +
      +
    2. +

      The member impls-for<when_all_t>::get-env is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class State, class Rcvr>(auto&&, State& state, const Receiver& rcvr) noexcept {
      +  return JOIN-ENV(
      +    MAKE-ENV(get_stop_token, state.stop_src.get_token()), get_env(rcvr));
      +}
      +
      +
    3. +

      The member impls-for<when_all_t>::get-state is initialized with a callable object equivalent to the following lambda +expression:

      +
      BUG: apply isn’t constrained
      +[]<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
      +  -> decltype(apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr))) {
      +  return apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr));
      +}
      +
      +

      where make-state is the following exposition-only class type:

      +
      template<class Sndr, class Env>
      +concept max-1-sender-in = sender_in<Sndr, Env> &&
      +  (tuple_size_v<value_types_of_t<Sndr, Env, tuple, tuple>> <= 1);
      +
      +enum class disposition { started, error, stopped };
      +
      +template <class Rcvr>
      +struct make-state {
      +  const env_of_t<Rcvr>& env;
      +
      +  template <max-1-sender-in<env_of_t<Rcvr>>... Sndrs>
      +  auto operator()(auto, auto, Sndrs&&... sndrs) const {
      +    using values_tuple = see below;
      +    using errors_variant = see below;
      +    using stop_token = stop_token_of_t<env_of_t<Rcvr>>;
      +    using stop_callback = stop_token::template callback_type<on-stop-request>;
      +
      +    struct state {
      +      void arrive(Rcvr& rcvr) noexcept {
      +        if (0 == --count) {
      +          complete(rcvr);
      +        }
      +      }
      +
      +      void complete(Rcvr& rcvr) noexcept; // see below
      +
      +      atomic<size_t> count{sizeof...(sndrs)};
      +      inplace_stop_source stop_src{};
      +      atomic<disposition> disp{disposition::started};
      +      errors_variant errors{};
      +      values_tuple values{};
      +      optional<stop_callback> on_stop{nullopt};
      +    };
      +
      +    return state{};
      +  }
      +};
      +
      +
        +
      1. +

        Let copy-fail be exception_ptr if decay-copying any of the + input senders' result datums can potentially throw; otherwise, none-such, where none-such is an unspecified + empty class type.

        +
      2. +

        The alias values_tuple denotes the type tuple<value_types_of_t<Sndrs, env_of_t<Rcvr>, decayed-tuple, optional>...> if that type is well-formed; + otherwise, tuple<>.

        +
      3. +

        The alias errors_variant denotes the type variant<none-such, copy-fail, Es...> with duplicate types removed, where Es is the pack of the decayed types of all the + input senders' possible error result datums.

        +
      4. +

        The member void state::complete(Rcvr& rcvr) noexcept behaves as follows:

        +
          +
        1. +

          If disp is equal to disposition::started, + evaluates:

          +
          auto tie = []<class... T>(tuple<T...>& t) noexcept { return tuple<T&...>(t); };
          +auto set = [&](auto&... t) noexcept { set_value(std::move(rcvr), std::move(t)...); };
          +
          +on_stop.reset();
          +apply(
          +  [&](auto&... opts) noexcept {
          +    apply(set, tuple_cat(tie(*opts)...));
          +  },
          +  values);
          +
          +
        2. +

          Otherwise, if disp is equal to disposition::error, evaluates:

          +
          on_stop.reset();
          +visit(
          +  [&]<class Error>(Error& error) noexcept {
          +    if constexpr (!same_as<Error, none-such>) {
          +      set_error(std::move(rcvr), std::move(error));
          +    }
          +  },
          +  errors);
          +
          +
        3. +

          Otherwise, evaluates:

          +
          on_stop.reset();
          +set_stopped(std::move(rcvr));
          +
          +
        +
      +
    4. +

      The member impls-for<when_all_t>::start is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class State, class Rcvr, class... Ops>(
      +    State& state, Rcvr& rcvr, Ops&... ops) noexcept -> void {
      +  state.on_stop.emplace(
      +    get_stop_token(get_env(rcvr)),
      +    on-stop-request{state.stop_src});
      +  if (state.stop_src.stop_requested()) {
      +    state.on_stop.reset();
      +    set_stopped(std::move(rcvr));
      +  } else {
      +    (start(ops), ...);
      +  }
      +}
      +
      +
    5. +

      The member impls-for<when_all_t>::complete is initialized with a callable object equivalent to the following lambda +expression:

      +
      []<class Index, class State, class Rcvr, class Set, class... Args>(
      +    this auto& complete, Index, State& state, Rcvr& rcvr, Set, Args&&... args) noexcept -> void {
      +  if constexpr (same_as<Set, set_error_t>) {
      +    if (disposition::error != state.disp.exchange(disposition::error)) {
      +      state.stop_src.request_stop();
      +      TRY-EMPLACE-ERROR(state.errors, std::forward<Args>(args)...);
      +    }
      +  } else if constexpr (same_as<Set, set_stopped_t>) {
      +    auto expected = disposition::started;
      +    if (state.disp.compare_exchange_strong(expected, disposition::stopped)) {
      +      state.stop_src.request_stop();
      +    }
      +  } else if constexpr (!same_as<decltype(State::values), tuple<>>) {
      +    if (state.disp == disposition::started) {
      +      auto& opt = get<Index::value>(state.values);
      +      TRY-EMPLACE-VALUE(complete, opt, std::forward<Args>(args)...);
      +    }
      +  }
      +
      +  state.arrive(rcvr);
      +}
      +
      +

      where TRY-EMPLACE-ERROR(v, e), for subexpressions v and e, is equivalent to:

      +
      try {
      +  v.template emplace<decltype(auto(e))>(e);
      +} catch (...) {
      +  v.template emplace<exception_ptr>(current_exception());
      +}
      +
      +

      if the expression decltype(auto(e))(e) is potentially throwing; otherwise, v.template emplace<decltype(auto(e))>(e); and where TRY-EMPLACE-VALUE(c, o, as...), for subexpressions c, o, and pack of subexpressions as, is equivalent to:

      +
      try {
      +  o.emplace(as...);
      +} catch (...) {
      +  c(Index(), state, rcvr, set_error, current_exception());
      +  return;
      +}
      +
      +

      if the expression decayed-tuple<decltype(as)...>{as...} is potentially throwing; otherwise, o.emplace(as...).

      +
    +
  5. +

    The expression when_all_with_variant(sndri...) is +expression-equivalent to:

    +
    transform_sender(
    +  CD(),
    +  make-sender(when_all_with_variant, {}, sndr0, ... sndrn-1));
    +
    +
  6. +

    Given subexpressions sndr and env, if sender-for<decltype((sndr)), when_all_with_variant_t> is false, +then the expression when_all_with_variant.transform_sender(sndr, env) is +ill-formed; otherwise, the body of the transform_sender member-function is equivalent to:

    +
    auto [tag, data, ...child] = sndr;
    +return when_all(into_variant(std::move(child))...);
    +
    +

    This causes the when_all_with_variant(sndr...) sender +to become when_all(into_variant(sndr)...) when it is connected with a +receiver with an execution domain that does not customize when_all_with_variant.

    +
+
34.9.11.11. execution::into_variant [exec.into.variant]
+
    +
  1. +

    into_variant adapts a sender with multiple value completion signatures into +a sender with just one consisting of a variant of tuples.

    +
  2. +

    The template into-variant-type computes the type sent by +a sender returned from into_variant.

    +
    namespace std::execution {
    +  template<class Sndr, class Env>
    +      requires sender_in<Sndr, Env>
    +    using into-variant-type =
    +      value_types_of_t<Sndr, Env>;
    +}
    +
    +
  3. +

    The name into_variant denotes a customization point object. For a +subexpression sndr, let Sndr be decltype((sndr)). If Sndr does not +satisfy sender, into_variant(sndr) is ill-formed.

    +
  4. +

    Otherwise, the expression into_variant(sndr) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(into_variant, {}, sndr))
    +
    +
  5. +

    The exposition-only class template impls-for ([exec.snd.general]) is +specialized for into_variant as follows:

    +
    namespace std::execution {
    +  template<>
    +  struct impls-for<into_variant_t> : default-impls {
    +    static constexpr auto get-state = see below;
    +    static constexpr auto complete = see below;
    +  };
    +}
    +
    +
      +
    1. +

      The member impls-for<into_variant_t>::get-state is +initialized with a callable object equivalent to the following lambda:

      +
      []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept
      +  -> type_identity<into-variant-type<child-type<Sndr>, env_of_t<Rcvr>>> {
      +  return {};
      +}
      +
      +
    2. +

      The member impls-for<into_variant_t>::complete is initialized with a callable object equivalent to the following lambda:

      +
      []<class State, class Rcvr, class Tag, class... Args>(
      +    auto, State, Rcvr& rcvr, Tag, Args&&... args) noexcept {
      +  if constexpr (same_as<Tag, set_value_t>) {
      +    using variant_type = typename State::type;
      +    using tuple_type = decayed-tuple<Args...>;
      +    try {
      +      set_value(std::move(rcvr),
      +                variant_type(tuple_type(std::forward<Args>(args)...)));
      +    }
      +    catch (...) {
      +      set_error(std::move(rcvr), current_exception());
      +    }
      +  } else {
      +    Tag()(std::move(rcvr), std::forward<Args>(args)...);
      +  }
      +}
      +
      +
    +
+
34.9.11.12. execution::stopped_as_optional [exec.stopped.as.optional]
+
    +
  1. +

    stopped_as_optional maps an input sender’s stopped completion operation into the value completion operation as an empty optional. The input sender’s value completion operation is also converted into an optional. The result is a sender that never completes with stopped, reporting cancellation by completing with an empty optional.

    +
  2. +

    The name stopped_as_optional denotes a customization point object. For a subexpression sndr, let Sndr be decltype((sndr)). +The expression stopped_as_optional(sndr) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(stopped_as_optional, {}, sndr))
    +
    +
  3. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)) and Env is decltype((env)). +If either sender-for<Sndr, stopped_as_optional_t> or single-sender<Sndr, Env> is false then the expression stopped_as_optional.transform_sender(sndr, env) is ill-formed; otherwise, it is equal to:

    +
    auto [tag, data, child] = sndr;
    +using V = single-sender-value-type<Sndr, Env>;
    +return let_stopped(
    +    then(std::move(child),
    +              []<class T>(T&& t) { return optional(std::forward(t)); }),
    +    []() noexcept { return just(optional()); });
    +
    +
+
34.9.11.13. execution::stopped_as_error [exec.stopped.as.error]
+
    +
  1. +

    stopped_as_error maps an input sender’s stopped completion operation into +an error completion operation as a custom error type. The result is a sender +that never completes with stopped, reporting cancellation by completing with +an error.

    +
  2. +

    The name stopped_as_error denotes a customization point object. For some subexpressions sndr and err, let Sndr be decltype((sndr)) and let Err be decltype((err)). If the type Sndr does not satisfy sender or if the type Err doesn’t satisfy movable-value, stopped_as_error(sndr, err) is ill-formed. Otherwise, the expression stopped_as_error(sndr, err) is expression-equivalent to:

    +
    transform_sender(
    +  get-domain-early(sndr),
    +  make-sender(stopped_as_error, err, sndr))
    +
    +
  3. +

    Let sndr and env be subexpressions such that Sndr is decltype((sndr)) and Env is decltype((env)). +If sender-for<Sndr, stopped_as_error_t> is false, then the expression stopped_as_error.transform_sender(sndr, env) is ill-formed; otherwise, it is equal to:

    +
    auto [tag, data, child] = sndr;
    +return let_stopped(
    +    std::move(child),
    +    [err = std::move(data)]() mutable { return just_error(std::move(err)); });
    +
    +
+

34.9.12. Sender consumers [exec.consumers]

+
34.9.12.1. execution::start_detached [exec.start.detached]
+
    +
  1. +

    start_detached eagerly starts a sender without the caller needing to manage +the lifetimes of any objects.

    +
  2. +

    The name start_detached denotes a customization point object. For a +subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, empty_env> is false, start_detached is ill-formed. +Otherwise, the expression start_detached(sndr) is expression-equivalent to +the following except that sndr is evaluated only once:

    +
    apply_sender(get-domain-early(sndr), start_detached, sndr)
    +
    +
      +
    • +

      Mandates: same_as<decltype(e), void> is true where e is the expression above.

      +
    +

    If the expression above does not eagerly start the sender sndr after +connecting it with a receiver that ignores value and stopped completion +operations and calls terminate() on error completions, the behavior of +calling start_detached(sndr) is undefined.

    +
  3. +

    Let sndr be a subexpression such that Sndr is decltype((sndr)), and let detached-receiver and detached-operation be the following exposition-only +class templates:

    +
    namespace std::execution {
    +  template<class Sndr>
    +  struct detached-receiver {
    +    using receiver_concept = receiver_t;
    +    detached-operation<Sndr>* op; // exposition only
    +
    +    void set_value() && noexcept { delete op; }
    +    void set_error() && noexcept { terminate(); }
    +    void set_stopped() && noexcept { delete op; }
    +    empty_env get_env() const noexcept { return {}; }
    +  };
    +
    +  template<class Sndr>
    +  struct detached-operation {
    +    connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only
    +
    +    explicit detached-operation(Sndr&& sndr)
    +      : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this}))
    +    {}
    +  };
    +}
    +
    +
  4. +

    If sender_to<Sndr, detached-receiver<Sndr>> is false, the +expression start_detached.apply_sender(sndr) is ill-formed; otherwise, it is +expression-equivalent to start((new detached-operation<Sndr>(sndr))->op).

    +
+
34.9.12.2. this_thread::sync_wait [exec.sync.wait]
+
    +
  1. +

    this_thread::sync_wait and this_thread::sync_wait_with_variant are used +to block the current thread of execution until the specified sender +completes and to return its async result. sync_wait mandates that the +input sender has exactly one value completion signature.

    +
  2. +

    Let sync-wait-env be the following exposition-only class +type:

    +
    namespace std::this_thread {
    +  struct sync-wait-env {
    +    execution::run_loop* loop; // exposition only
    +
    +    auto query(execution::get_scheduler_t) const noexcept { loop->get_scheduler(); }
    +    auto query(execution::get_delegatee_scheduler_t) const noexcept { loop->get_scheduler(); }
    +  };
    +}
    +
    +
  3. +

    Let sync-wait-result-type and sync-wait-with-variant-result-type be exposition-only +template aliases defined as follows:

    +
    namespace std::this_thread {
    +  template<execution::sender_in<sync-wait-env> Sndr>
    +    using sync-wait-result-type =
    +      optional<execution::value_types_of_t<Sndr, sync-wait-env, decayed-tuple, type_identity_t>>;
    +
    +  template<execution::sender_in<sync-wait-env> Sndr>
    +    using sync-wait-with-variant-result-type =
    +      optional<execution::into-variant-type<Sndr, sync-wait-env>>; // see [exec.into.variant]
    +}
    +
    +
  4. +

    The name this_thread::sync_wait denotes a customization point object. For a +subexpression sndr, let Sndr be decltype((sndr)). If sender_in<Sndr, sync-wait-env> is false, the +expression this_thread::sync_wait(sndr) is ill-formed. Otherwise, it is +expression-equivalent to the following, except that sndr is evaluated only +once:

    +
    apply_sender(get-domain-early(sndr), sync_wait, sndr)
    +
    +

    Mandates:

    +
      +
    • +

      The type sync-wait-result-type<Sndr> is well-formed.

      +
    • +

      same_as<decltype(e), sync-wait-result-type<Sndr>> is true, where e is apply_sender the expression above.

      +
    +
  5. +

    Let sync-wait-state and sync-wait-receiver be the following exposition-only class +templates:

    +
    namespace std::this_thread {
    +  template<class Sndr>
    +  struct sync-wait-state { // exposition only
    +    execution::run_loop loop;
    +    exception_ptr error;
    +    sync-wait-result-type<Sndr> result;
    +  };
    +
    +  template<class Sndr>
    +  struct sync-wait-receiver {
    +    using receiver_concept = execution::receiver_t;
    +    sync-wait-state<Sndr>* state; // exposition only
    +
    +    template<class... Args>
    +    void set_value(Args&&... args) && noexcept;
    +
    +    template<class Error>
    +    void set_error(Error&& err) && noexcept;
    +
    +    void set_stopped() && noexcept;
    +
    +    sync-wait-env get_env() const noexcept { return {&state->loop}; }
    +  };
    +}
    +
    +
      +
    1. +
      template<class... Args>
      +void set_value(Args&&... args) && noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to:

        +
        try {
        +  state->result.emplace(std::forward<Args>(args)...);
        +} catch (...) {
        +  state->error = current_exception();
        +}
        +state->loop.finish();
        +
        +
      +
    2. +
      template<class Error>
      +void set_error(Error&& err) && noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to:

        +
        state->error = AS-EXCEPT-PTR(std::forward<Error>(err)); // see [exec.general]
        +state->loop.finish();
        +
        +
      +
    3. +
      template<class Error>
      +void set_stopped() && noexcept;
      +
      +
        +
      1. +

        Effects: Equivalent to state->loop.finish().

        +
      +
    +
  6. +

    For a subexpression sndr, let Sndr be decltype((sndr)). If sender_to<Sndr, sync-wait-receiver<Sndr>> is false, the +expression sync_wait.apply_sender(sndr) is ill-formed; otherwise, it is +equivalent to:

    +
    sync-wait-state<Sndr> state;
    +auto op = connect(sndr, sync-wait-receiver<Sndr>{&state});
    +start(op);
    +
    +state.loop.run();
    +if (state.error) {
    +  rethrow_exception(std::move(state.error));
    +}
    +return std::move(state.result);
    +
    +
  7. +

    The behavior of this_thread::sync_wait(sndr) is undefined unless:

    +
      +
    1. +

      It blocks the current thread of execution ([defns.block]) with forward +progress guarantee delegation ([intro.progress]) until the specified +sender completes. The default implementation of sync_wait achieves forward progress guarantee delegation by providing +a run_loop scheduler via the get_delegatee_scheduler query on the sync-wait-receiver’s environment. The run_loop is +driven by the current thread of execution.

      +
    2. +

      It returns the specified sender’s async results as follows:

      +
        +
      1. +

        For a value completion, the result datums are returned +in a tuple in an engaged optional object.

        +
      2. +

        For an error completion, the result datum is rethrown.

        +
      3. +

        For a stopped completion, a disengaged optional object is returned.

        +
      +
    +
  8. +

    The name this_thread::sync_wait_with_variant denotes a customization point +object. For a subexpression sndr, let Sndr be the type of into_variant(sndr). If sender_in<Sndr, sync-wait-env> is false, this_thread::sync_wait_with_variant(sndr) is ill-formed. Otherwise, it is +expression-equivalent to the following, except sndr is evaluated only +once:

    +
    apply_sender(get-domain-early(sndr), sync_wait_with_variant, sndr)
    +
    +

    Mandates:

    +
      +
    • +

      The type sync-wait-with-variant-result-type<Sndr> is +well-formed.

      +
    • +

      same_as<decltype(e), sync-wait-with-variant-result-type<Sndr>> is true, +where e is the expression above.

      +
    +
  9. +

    If callable<sync_wait_t, Sndr> is false, the +expression sync_wait_with_variant.apply_sender(sndr) is ill-formed. +Otherwise, it is equivalent to:

    +
    using result_type = sync-wait-with-variant-result-type<Sndr>;
    +if (auto opt_value = sync_wait(into_variant(sndr))) {
    +  return result_type(std::move(get<0>(*opt_value)));
    +}
    +return result_type(nullopt);
    +
    +
  10. +

    The behavior of this_thread::sync_wait_with_variant(sndr) is undefined unless:

    +
      +
    1. +

      It blocks the current thread of execution ([defns.block]) with forward +progress guarantee delegation ([intro.progress]) until the specified +sender completes. The default implementation of sync_wait_with_variant achieves forward progress guarantee delegation +by relying on the forward progress guarantee delegation provided by sync_wait.

      +
    2. +

      It returns the specified sender’s async results as follows:

      +
        +
      1. +

        For a value completion, the result datums are returned in an engaged optional object that contains a variant of tuples.

        +
      2. +

        For an error completion, the result datum is rethrown.

        +
      3. +

        For a stopped completion, a disengaged optional object is returned.

        +
      +
    +
+

34.10. execution::execute [exec.execute]

+
    +
  1. +

    execute executes a specified callable object on a specified scheduler.

    +
  2. +

    The name execute denotes a customization point object. For some +subexpressions sch and f, let Sch be decltype((sch)) and F be the +decayed type of f. If Sch does not satisfy scheduler or F does not +satisfy invocable, execute(sch, f) is ill-formed. Otherwise, execute(sch, f) is expression-equivalent to:

    +
    apply_sender(
    +  query-or-default(get_domain, sch, default_domain()),
    +  execute, schedule(sch), f)
    +
    +
      +
    • +

      Mandates: The type of the expression above is void.

      +
    +
  3. +

    For some subexpressions sndr and f where F is the decayed type of f, +if F does not satisfy invocable, the expression execute.apply_sender(sndr, f) is ill-formed; otherwise it is +expression-equivalent to start_detached(then(sndr, f)).

    +
+

34.11. Sender/receiver utilities [exec.utils]

+

34.11.1. execution::completion_signatures [exec.utils.cmplsigs]

+
    +
  1. +

    completion_signatures is a type that encodes a set of completion signatures +([async.ops]).

    +
  2. +

    [Example:

    +
    class my_sender {
    +  using completion_signatures =
    +    completion_signatures<
    +      set_value_t(),
    +      set_value_t(int, float),
    +      set_error_t(exception_ptr),
    +      set_error_t(error_code),
    +      set_stopped_t()>;
    +};
    +
    +// Declares my_sender to be a sender that can complete by calling
    +// one of the following for a receiver expression rcvr:
    +//    set_value(rcvr)
    +//    set_value(rcvr, int{...}, float{...})
    +//    set_error(rcvr, exception_ptr{...})
    +//    set_error(rcvr, error_code{...})
    +//    set_stopped(rcvr)
    +
    +

    -- end example]

    +
  3. +

    This subclause makes use of the following exposition-only entities:

    +
    template<class Fn>
    +  concept completion-signature = see below;
    +
    +template<bool>
    +  struct indirect-meta-apply {
    +    template<template<class...> class T, class... As>
    +      using meta-apply = T<As...>; // exposition only
    +  };
    +
    +template<class...>
    +  concept always-true = true; // exposition only
    +
    +
      +
    1. +

      A type Fn satisfies completion-signature if and +only if it is a function type with one of the following forms:

      +
        +
      • +

        set_value_t(Vs...), where Vs is an arbitrary parameter pack.

        +
      • +

        set_error_t(Err), where Err is +an arbitrary type.

        +
      • +

        set_stopped_t()

        +
      +
    +
    template<class Tag,
    +          valid-completion-signatures Completions,
    +          template<class...> class Tuple,
    +          template<class...> class Variant>
    +  using gather-signatures = see below;
    +
    +
      +
    1. +

      Let Fns... be a template parameter pack of the arguments of the completion_signatures specialization named by Completions, let TagFns be a template parameter pack of the function +types in Fns whose return types are Tag, and let Tsn be a template parameter pack +of the function argument types in the n-th type in TagFns. Then, given two variadic templates Tuple and Variant, the type gather-signatures<Tag, Completions, Tuple, Variant> names the type META-APPLY(Variant, META-APPLY(Tuple, Ts0...), META-APPLY(Tuple, Ts1...), ... META-APPLY(Tuple, Tsm-1...)), where m is the size of the parameter pack TagFns and META-APPLY(T, As...) is equivalent to:

      +
      typename indirect-meta-apply<always-true<As...>>::template meta-apply<T, As...>;
      +
      +
    2. +

      The purpose of META-APPLY is +to make it valid to use non-variadic templates as Variant and Tuple arguments to gather-signatures.

      +
    +
  4. +
    namespace std::execution {
    +  template<completion-signature... Fns>
    +    struct completion_signatures {};
    +
    +  template<class Sndr,
    +            class Env = empty_env,
    +            template<class...> class Tuple = decayed-tuple,
    +            template<class...> class Variant = variant-or-empty>
    +      requires sender_in<Sndr, Env>
    +    using value_types_of_t =
    +        gather-signatures<set_value_t, completion_signatures_of_t<Sndr, Env>, Tuple, Variant>;
    +
    +  template<class Sndr,
    +            class Env = empty_env,
    +            template<class...> class Variant = variant-or-empty>
    +      requires sender_in<Sndr, Env>
    +    using error_types_of_t =
    +        gather-signatures<set_error_t, completion_signatures_of_t<Sndr, Env>, type_identity_t, Variant>;
    +
    +  template<class Sndr, class Env = empty_env>
    +      requires sender_in<Sndr, Env>
    +    inline constexpr bool sends_stopped =
    +        !same_as<
    +          type-list<>,
    +          gather-signatures<set_stopped_t, completion_signatures_of_t<Sndr, Env>, type-list, type-list>>;
    +}
    +
    +
+

34.11.2. execution::transform_completion_signatures [exec.utils.tfxcmplsigs]

+
    +
  1. +

    transform_completion_signatures is an alias template used to transform one +set of completion signatures into another. It takes a set of completion +signatures and several other template arguments that apply modifications to +each completion signature in the set to generate a new specialization of completion_signatures.

    +
  2. +

    [Example:

    +
    // Given a sender Sndr and an environment Env, adapt the completion
    +// signatures of Sndr by lvalue-ref qualifying the values, adding an additional
    +// exception_ptr error completion if its not already there, and leaving the
    +// other completion signatures alone.
    +template<class... Args>
    +  using my_set_value_t =
    +    completion_signatures<
    +      set_value_t(add_lvalue_reference_t<Args>...)>;
    +
    +using my_completion_signatures =
    +  transform_completion_signatures<
    +    completion_signatures_of_t<Sndr, Env>,
    +    completion_signatures<set_error_t(exception_ptr)>,
    +    my_set_value_t>;
    +
    +

    -- end example]

    +
  3. +

    This subclause makes use of the following exposition-only entities:

    +
    template<class... As>
    +  using default-set-value =
    +    completion_signatures<set_value_t(As...)>;
    +
    +template<class Err>
    +  using default-set-error =
    +    completion_signatures<set_error_t(Err)>;
    +
    +
  4. +
    namespace std::execution {
    +  template<valid-completion-signatures InputSignatures,
    +          valid-completion-signatures AdditionalSignatures =
    +              completion_signatures<>,
    +          template<class...> class SetValue = default-set-value,
    +          template<class> class SetError = default-set-error,
    +          valid-completion-signatures SetStopped =
    +              completion_signatures<set_stopped_t()>>
    +  using transform_completion_signatures =
    +    completion_signatures<see below>;
    +}
    +
    +
      +
    1. +

      SetValue shall name an alias template such that for any template +parameter pack As..., the type SetValue<As...> is either ill-formed +or else valid-completion-signatures<SetValue<As...>> is satisfied.

      +
    2. +

      SetError shall name an alias template such that for any type Err, SetError<Err> is either ill-formed or else valid-completion-signatures<SetError<Err>> is +satisfied.

      +
    +

    Then:

    +
      +
    1. +

      Let Vs... be a pack of the types in the type-list named by gather-signatures<set_value_t, InputSignatures, SetValue, type-list>.

      +
    2. +

      Let Es... be a pack of the types in the type-list named by gather-signatures<set_error_t, InputSignatures, type_identity_t, error-list>, where error-list is an alias template such that error-list<Ts...> names type-list<SetError<Ts>...>.

      +
    3. +

      Let Ss name the type completion_signatures<> if gather-signatures<set_stopped_t, InputSignatures, type-list, type-list> is an alias for the type type-list<>; otherwise, SetStopped.

      +
    +

    Then:

    +
      +
    1. +

      If any of the above types are ill-formed, then transform_completion_signatures<InputSignatures, AdditionalSignatures, SetValue, SetError, SetStopped> is ill-formed,

      +
    2. +

      Otherwise, transform_completion_signatures<InputSignatures, AdditionalSignatures, SetValue, SetError, SetStopped> names the type completion_signatures<Sigs...> where Sigs... is the unique set of +types in all the template arguments of all the completion_signatures specializations in [AdditionalSignatures, Vs..., Es..., Ss].

      +
    +
+

34.12. Execution contexts [exec.ctx]

+
    +
  1. +

    This subclause specifies some execution resources on which work can be +scheduled.

    +
+

34.12.1. run_loop [exec.run.loop]

+
    +
  1. +

    A run_loop is an execution resource on which work can be scheduled. It +maintains a simple, thread-safe first-in-first-out queue of work. Its run() member function removes elements from the queue and executes them in a loop +on whatever thread of execution calls run().

    +
  2. +

    A run_loop instance has an associated count that corresponds to the +number of work items that are in its queue. Additionally, a run_loop has an +associated state that can be one of starting, running, +or finishing.

    +
  3. +

    Concurrent invocations of the member functions of run_loop, other than run and its destructor, do not introduce data races. The member functions pop_front, push_back, and finish execute atomically.

    +
  4. +

    Implementations are encouraged to use an intrusive +queue of operation states to hold the work units to make scheduling +allocation-free.

    +
    namespace std::execution {
    +  class run_loop {
    +    // [exec.run.loop.types] Associated types
    +    class run-loop-scheduler; // exposition only
    +    class run-loop-sender; // exposition only
    +    struct run-loop-opstate-base { // exposition only
    +      virtual void execute() = 0;
    +      run_loop* loop;
    +      run-loop-opstate-base* next;
    +    };
    +    template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
    +      using run-loop-opstate = unspecified; // exposition only
    +
    +    // [exec.run.loop.members] Member functions:
    +    run-loop-opstate-base* pop_front(); // exposition only
    +    void push_back(run-loop-opstate-base*); // exposition only
    +
    +  public:
    +    // [exec.run.loop.ctor] construct/copy/destroy
    +    run_loop() noexcept;
    +    run_loop(run_loop&&) = delete;
    +    ~run_loop();
    +
    +    // [exec.run.loop.members] Member functions:
    +    run-loop-scheduler get_scheduler();
    +    void run();
    +    void finish();
    +  };
    +}
    +
    +
+
34.12.1.1. Associated types [exec.run.loop.types]
+
class run-loop-scheduler;
+
+
    +
  1. +

    run-loop-scheduler is an unspecified type that models +the scheduler concept.

    +
  2. +

    Instances of run-loop-scheduler remain valid until the +end of the lifetime of the run_loop instance from which they were +obtained.

    +
  3. +

    Two instances of run-loop-scheduler compare equal if +and only if they were obtained from the same run_loop instance.

    +
  4. +

    Let sch be an expression of type run-loop-scheduler. The expression schedule(sch) is not potentially-throwing and has type run-loop-sender.

    +
+
class run-loop-sender;
+
+
    +
  1. +

    run-loop-sender is an unspecified type such that sender-of<run-loop-sender> is true. +Additionally, the types reported by its error_types associated type is exception_ptr, and the value of its sends_stopped trait is true.

    +
  2. +

    An instance of run-loop-sender remains valid until the +end of the lifetime of its associated run_loop instance.

    +
  3. +

    Let sndr be an expression of type run-loop-sender, let rcvr be an +expression such that decltype(rcvr) models the receiver_of concept, and let C be either set_value_t or set_stopped_t. Then:

    +
      +
    • +

      The expression connect(sndr, rcvr) has type run-loop-opstate<decay_t<decltype(rcvr)>> and is potentially-throwing if and only if the initialiation of decay_t<decltype(rcvr)> from rcvr is potentially-throwing.

      +
    • +

      The expression get_completion_scheduler<C>(get_env(sndr)) is +not potentially-throwing, has type run-loop-scheduler, and compares equal to the run-loop-scheduler instance from which sndr was obtained.

      +
    +
+
template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
+  struct run-loop-opstate;
+
+
    +
  1. +

    run-loop-opstate<Rcvr> inherits unambiguously +from run-loop-opstate-base.

    +
  2. +

    Let o be a non-const lvalue of type run-loop-opstate<Rcvr>, and let REC(o) be a non-const lvalue reference to an +instance of type Rcvr that was initialized with the +expression rcvr passed to the invocation of connect that returned o. Then:

    +
      +
    • +

      The object to which REC(o) refers remains +valid for the lifetime of the object to which o refers.

      +
    • +

      The type run-loop-opstate<Rcvr> overrides run-loop-opstate-base::execute() such that o.execute() is equivalent to the following:

      +
      if (get_stop_token(REC(o)).stop_requested()) {
      +  set_stopped(std::move(REC(o)));
      +} else {
      +  set_value(std::move(REC(o)));
      +}
      +
      +
    • +

      The expression start(o) is equivalent to the +following:

      +
      try {
      +  o.loop->push_back(&o);
      +} catch(...) {
      +  set_error(std::move(REC(o)), current_exception());
      +}
      +
      +
    +
+
34.12.1.2. Constructor and destructor [exec.run.loop.ctor]
+
run_loop() noexcept;
+
+
    +
  1. +

    Postconditions: count is 0 and state is starting.

    +
+
~run_loop();
+
+
    +
  1. +

    Effects: If count is not 0 or if state is running, invokes terminate(). Otherwise, has no effects.

    +
+
34.12.1.3. Member functions [exec.run.loop.members]
+
run-loop-opstate-base* pop_front();
+
+
    +
  1. +

    Effects: Blocks ([defns.block]) until one of the following conditions +is true:

    +
      +
    • +

      count is 0 and state is finishing, in which case pop_front returns nullptr; or

      +
    • +

      count is greater than 0, in which case an item is removed from +the front of the queue, count is decremented by 1, and the +removed item is returned.

      +
    +
+
void push_back(run-loop-opstate-base* item);
+
+
    +
  1. +

    Effects: Adds item to the back of the queue and increments count by 1.

    +
  2. +

    Synchronization: This operation synchronizes with the pop_front operation that obtains item.

    +
+
run-loop-scheduler run_loop::get_scheduler();
+
+
    +
  1. +

    Returns: an instance of run-loop-scheduler that +can be used to schedule work onto this run_loop instance.

    +
+
void run();
+
+
    +
  1. +

    Effects: Equivalent to:

    +
    while (auto* op = pop_front()) {
    +  op->execute();
    +}
    +
    +
  2. +

    Precondition: state is starting.

    +
  3. +

    Postcondition: state is finishing.

    +
  4. +

    Remarks: While the loop is executing, state is running. +When state changes, it does so without introducing data races.

    +
+
void finish();
+
+
    +
  1. +

    Effects: Changes state to finishing.

    +
  2. +

    Synchronization: This operation synchronizes with all pop_front operations on this object.

    +
+

34.13. Coroutine utilities [exec.coro.utils]

+

34.13.1. execution::as_awaitable [exec.as.awaitable]

+
    +
  1. +

    as_awaitable transforms an object into one that is awaitable within a +particular coroutine. This subclause makes use of the following +exposition-only entities:

    +
    namespace std::execution {
    +  template<class Sndr, class Env>
    +    using single-sender-value-type = see below;
    +
    +  template<class Sndr, class Env>
    +    concept single-sender =
    +      sender_in<Sndr, Env> &&
    +      requires { typename single-sender-value-type<Sndr, Env>; };
    +
    +  template<class Sndr, class Promise>
    +    concept awaitable-sender =
    +      single-sender<Sndr, env_of_t> &&
    +      sender_to<Sndr, awaitable-receiver> && // see below
    +      requires (Promise& p) {
    +        { p.unhandled_stopped() } -> convertible_to<coroutine_handle<>>;
    +      };
    +
    +  template<class Sndr, class Promise>
    +    class sender-awaitable;
    +}
    +
    +
      +
    1. +

      Alias template single-sender-value-type is defined as follows:

      +
        +
      1. +

        If value_types_of_t<Sndr, Env, Tuple, Variant> would have the form Variant<Tuple<T>>, then single-sender-value-type<Sndr, Env> is an +alias for type decay_t<T>.

        +
      2. +

        Otherwise, if value_types_of_t<Sndr, Env, Tuple, Variant> would +have the form Variant<Tuple<>> or Variant<>, then single-sender-value-type<Sndr, Env> is an +alias for type void.

        +
      3. +

        Otherwise, if value_types_of_t<Sndr, Env, Tuple, Variant> would +have the form Variant<Tuple<Ts...>> where Ts is a parameter pack, +then single-sender-value-type<Sndr, Env> is an +alias for type std::tuple<decay_t<Ts>...>.

        +
      4. +

        Otherwise, single-sender-value-type<Sndr, Env> is ill-formed.

        +
      +
    2. +

      The type sender-awaitable<Sndr, Promise> is +equivalent to the following:

      +
      namespace std::execution {
      +  template<class Sndr, class Promise>
      +  class sender-awaitable {
      +    struct unit {};                                          // exposition only
      +    using value-type =                                       // exposition only
      +      single-sender-value-type<Sndr, env_of_t<Promise>>;
      +    using result-type =                                      // exposition only
      +      conditional_t<is_void_v<value-type>, unit, value-type>;
      +    struct awaitable-receiver;                               // exposition only
      +
      +    variant<monostate, result-type, exception_ptr> result{}; // exposition only
      +    connect_result_t<Sndr, awaitable-receiver> state;        // exposition only
      +
      +  public:
      +    sender-awaitable(Sndr&& sndr, Promise& p);
      +    static constexpr bool await_ready() noexcept { return false; }
      +    void await_suspend(coroutine_handle<Promise>) noexcept { start(state); }
      +    value-type await_resume();
      +  };
      +}
      +
      +
        +
      1. +

        awaitable-receiver is equivalent to the following:

        +
        struct awaitable-receiver {
        +  using receiver_concept = receiver_t;
        +  variant<monostate, result-type, exception_ptr>* result-ptr; // exposition only
        +  coroutine_handle<Promise> continuation;                     // exposition only
        +  // ... see below
        +};
        +
        +

        Let rcvr be an rvalue expression of type awaitable-receiver, let crcvr be a const lvalue that refers to rcvr, let vs be a parameter pack of types Vs..., and let err be an arbitrary expression of type Err. +Then:

        +
          +
        1. +

          If constructible_from<result-type, Vs...> is satisfied, the expression set_value(rcvr, vs...) is +equivalent to:

          +
          try {
          +  rcvr.result-ptr->emplace<1>(vs...);
          +} catch(...) {
          +  rcvr.result-ptr->emplace<2>(current_exception());
          +}
          +rcvr.continuation.resume();
          +
          +

          Otherwise, set_value(rcvr, vs...) is ill-formed.

          +
        2. +

          The expression set_error(rcvr, err) is equivalent to:

          +
          rcvr.result-ptr->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
          +rcvr.continuation.resume();
          +
          +
        3. +

          The expression set_stopped(rcvr) is equivalent to static_cast<coroutine_handle<>>(rcvr.continuation.promise().unhandled_stopped()).resume().

          +
        4. +

          For any expression tag whose type satisfies forwarding-query and for any pack of +subexpressions as, get_env(crcvr).query(tag, as...) is +expression-equivalent to tag(get_env(as_const(crcvr.continuation.promise())), as...) when that expression is well-formed.

          +
        +
      2. +

        sender-awaitable(Sndr&& sndr, Promise& p)

        +
          +
        • +

          Effects: initializes state with connect(std::forward<Sndr>(sndr), awaitable-receiver{&result, coroutine_handle<Promise>::from_promise(p)}).

          +
        +
      3. +

        value-type await_resume()

        +
          +
        • +

          Effects: equivalent to:

          +
          if (result.index() == 2)
          +  rethrow_exception(get<2>(result));
          +if constexpr (!is_void_v<value-type>)
          +  return std::forward<value-type>(get<1>(result));
          +
          +
        +
      +
    +
  2. +

    as_awaitable is a customization point object. For some subexpressions expr and p where p is an lvalue, Expr names the type decltype((expr)) and Promise names the type decltype((p)), as_awaitable(expr, p) is expression-equivalent to the following:

    +
      +
    1. +

      expr.as_awaitable(p) if that expression is well-formed.

      +
        +
      • +

        Mandates: is-awaitable<A, Promise> is true, where A is the type of the expression above.

        +
      +
    2. +

      Otherwise, expr if is-awaitable<Expr, U> is true, where U is an unspecified class type that +lacks a member named await_transform. The +condition is not is-awaitable<Expr, Promise> as +that creates the potential for constraint recursion.

      +
        +
      • +

        Preconditions: is-awaitable<Expr, Promise> is true and the expression co_await expr in a +coroutine with promise type U is +expression-equivalent to the same expression in a coroutine with +promise type Promise.

        +
      +
    3. +

      Otherwise, sender-awaitable{expr, p} if awaitable-sender<Expr, Promise> is true.

      +
    4. +

      Otherwise, expr.

      +
    +
+

34.13.2. execution::with_awaitable_senders [exec.with.awaitable.senders]

+
    +
  1. +

    with_awaitable_senders, when used as the base class of a coroutine promise +type, makes senders awaitable in that coroutine type.

    +

    In addition, it provides a default implementation of unhandled_stopped() such that if a sender completes by calling set_stopped, it is treated as +if an uncatchable "stopped" exception were thrown from the await-expression. In practice, the coroutine is never resumed, and +the unhandled_stopped of the coroutine caller’s promise type is called.

    +
    namespace std::execution {
    +  template<class-type Promise>
    +    struct with_awaitable_senders {
    +      template<OtherPromise>
    +        requires (!same_as<OtherPromise, void>)
    +      void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
    +
    +      coroutine_handle<> continuation() const noexcept { return continuation; }
    +
    +      coroutine_handle<> unhandled_stopped() noexcept {
    +        return stopped-handler(continuation.address());
    +      }
    +
    +      template<class Value>
    +      see below await_transform(Value&& value);
    +
    +      private:
    +      // exposition only
    +      [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
    +        terminate();
    +      }
    +      coroutine_handle<> continuation{}; // exposition only
    +      // exposition only
    +      coroutine_handle<> (*stopped-handler)(void*) noexcept = &default_unhandled_stopped;
    +    };
    +}
    +
    +
  2. +

    void set_continuation(coroutine_handle<OtherPromise> h) noexcept

    +
      +
    • +

      Effects: equivalent to:

      +
    +
    continuation = h;
    +if constexpr ( requires(OtherPromise& other) { other.unhandled_stopped(); } ) {
    +  stopped-handler = [](void* p) noexcept -> coroutine_handle<> {
    +    return coroutine_handle<OtherPromise>::from_address(p)
    +      .promise().unhandled_stopped();
    +  };
    +} else {
    +  stopped-handler = default_unhandled_stopped;
    +}
    +
    +
  3. +

    call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value)

    +
      +
    • +

      Effects: equivalent to:

      +
    +
    return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));
    +
    +
+
+
+
+ +

Index

+

Terms defined by this specification

+ +

References

+

Informative References

+
+
[HPX] +
Hartmut Kaiser; et al. HPX - The C++ Standard Library for Parallelism and Concurrency. URL: https://doi.org/10.21105/joss.02352 +
[N4885] +
Thomas Köppe. Working Draft, Standard for Programming Language C++. 17 March 2021. URL: https://wg21.link/n4885 +
[P0443R14] +
Jared Hoberock, Michael Garland, Chris Kohlhoff, Chris Mysen, H. Carter Edwards, Gordon Brown, D. S. Hollman. A Unified Executors Proposal for C++. 15 September 2020. URL: https://wg21.link/p0443r14 +
[P0981R0] +
Richard Smith, Gor Nishanov. Halo: coroutine Heap Allocation eLision Optimization: the joint response. 18 March 2018. URL: https://wg21.link/p0981r0 +
[P1056R1] +
Lewis Baker, Gor Nishanov. Add lazy coroutine (coroutine task) type. 7 October 2018. URL: https://wg21.link/p1056r1 +
[P1895R0] +
Lewis Baker, Eric Niebler, Kirk Shoop. tag_invoke: A general pattern for supporting customisable functions. 8 October 2019. URL: https://wg21.link/p1895r0 +
[P1897R3] +
Lee Howes. Towards C++23 executors: A proposal for an initial set of algorithms. 16 May 2020. URL: https://wg21.link/p1897r3 +
[P2175R0] +
Lewis Baker. Composable cancellation for sender-based async operations. 15 December 2020. URL: https://wg21.link/p2175r0 +
+ + + + + + + + + + + + + + \ No newline at end of file diff --git a/execution.bs b/execution.bs index cca5487..c157ac7 100644 --- a/execution.bs +++ b/execution.bs @@ -1,9 +1,9 @@
@@ -4192,7 +4193,7 @@ declarations into the `` synopsis:
 namespace std {
 
// [stoptoken.concepts], stop token concepts - template<class Callback, class Token, class Initializer = Callback> + template<class CallbackFn, class Token, class Initializer = CallbackFn> concept stoppable-callback-for = see below; // exposition only template<class Token> @@ -4216,7 +4217,7 @@ namespace std { inline constexpr nostopstate_t nostopstate{}; // 33.3.5, class template stop_callback - template<class Callback> + template<class CallbackFn> class stop_callback;
// [stoptoken.never], class never_stop_token @@ -4229,11 +4230,11 @@ namespace std { class inplace_stop_source; // [stopcallback.inplace], class template inplace_stop_callback - template<class Callback> + template<class CallbackFn> class inplace_stop_callback; - template<class T, class Callback> - using stop_callback_for_t = T::template callback_type<Callback>;
+ template<class T, class CallbackFn> + using stop_callback_for_t = T::template callback_type<CallbackFn>;
}
@@ -4247,105 +4248,101 @@ Header `` synopsis [thread.stoptoken.syn] and Class ### Stop token concepts [stoptoken.concepts] ### {#spec-stoptoken.concepts} -1. For a stop token type `Token` and a type `Callback` that is callable with no - arguments, if the type `stop_callback_for_t` is valid, it - denotes the type of a stop callback to use to register a callback to be - executed if a stop request is ever made on the `stoppable_token`'s - associated stop source. The exposition-only `stoppable-callback-for` - concept checks for a callback compatible with a given stop token type. +1. For a stop token type `Token` and a type `CallbackFn` such that + invocable<CallbackFn> is `true`, if the type + `stop_callback_for_t` is valid, it denotes the type of a + stop callback to use when registering a callback invocation to be executed + if a stop request is made on the `stoppable_token`'s associated stop source. + The exposition-only `stoppable-callback-for` concept checks for a + callback compatible with a given stop token type.
-    template<class Callback, class Token, class Initializer = Callback>
+    template<class CallbackFn, class Token, class Initializer = CallbackFn>
       concept stoppable-callback-for = // exposition only
-        invocable<Callback> &&
-        constructible_from<Callback, Initializer> &&
-        requires { typename stop_callback_for_t<Token, Callback>; } &&
-        constructible_from<stop_callback_for_t<Token, Callback>, const Token&, Initializer>;
+        invocable<CallbackFn> &&
+        constructible_from<CallbackFn, Initializer> &&
+        requires { typename stop_callback_for_t<Token, CallbackFn>; } &&
+        constructible_from<stop_callback_for_t<Token, CallbackFn>, const Token&, Initializer>;
     
2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the same logical stop state; let `init` be an object of type - `Initializer`; and let `CB` denote the type `stop_callback_for_t`. + `Initializer`; and let `SCB` denote the type `stop_callback_for_t`. -3. The concept stoppable-callback-for<Callback, Token, +3. The concept stoppable-callback-for<CallbackFn, Token, Initializer> is modeled only if: 1. The following concepts are modeled: - * `constructible_from` - * `constructible_from` - * `constructible_from` + * `constructible_from` + * `constructible_from` + * `constructible_from` - 2. An object of type `CB` has an associated callback - function of type `Callback`. Let `cb` be an object of type `CB` - and let `callback` denote `cb`'s associated callback function. - Direct-non-list-initializing `cb` from arguments `t` and `init` shall + 2. An object of type `SCB` has an associated callback + function of type `CallbackFn`. Let `scb` be an object of type `SCB` + and let `cbfn` denote `scb`'s associated callback function. + Direct-non-list-initializing `scb` from arguments `t` and `init` shall execute a stoppable callback registration as follows: 1. If `t.stop_possible()` is `true`: - 1. `callback` shall be direct-initialized with `init`. + 1. `cbfn` shall be direct-initialized with `init`. - 2. Construction of `cb` shall only throw exceptions thrown by the - initialization of `callback` from `init`. + 2. Construction of `scb` shall only throw exceptions thrown by the + initialization of `cbfn` from `init`. 3. The callback invocation - std::forward<Callback>(callback)() shall + std::forward<CallbackFn>(cbfn)() shall be registered with `t`'s associated stop state as follows: 1. If `t.stop_requested()` evaluates to `false` at the time of registration, the callback invocation is added to the stop state's list of callbacks such that - std::forward<Callback>(callback)() is + std::forward<CallbackFn>(cbfn)() is evaluated if a stop request is made on the stop state. 2. Otherwise, - std::forward<Callback>(callback)() + std::forward<CallbackFn>(cbfn)() shall be immediately evaluated on the thread executing - `cb`'s constructor, and the callback invocation shall not be + `scb`'s constructor, and the callback invocation shall not be added to the list of callback invocations. 4. If the callback invocation was added to stop state's list of - callbacks, `cb` shall be associated with the stop state. + callbacks, `scb` shall be associated with the stop state. 2. If `t.stop_possible()` is `false`, there is no - requirement that the initialization of `cb` causes the - initialization of `callback`. + requirement that the initialization of `scb` causes the + initialization of `cbfn`.
- 3. An evaluation of `u.stop_requested()` that strongly happens after - ([intro.races]/10) the beginning of the invocation of `callback` - shall return `true`. - - 4. Destruction of `cb` shall execute a stoppable callback + 3. Destruction of `scb` shall execute a stoppable callback deregistration as follows: - 1. If the constructor of `cb` did not register a callback invocation + 1. If the constructor of `scb` did not register a callback invocation with `t`'s stop state, then the stoppable callback deregistration shall have no effect. - 2. Otherwise, the invocation of `callback` shall be removed from + 2. Otherwise, the invocation of `cbfn` shall be removed from the associated stop state. - 3. If `callback` is currently being invoked on another thread + 3. If `cbfn` is concurrently executing on another thread then the stoppable callback deregistration shall block - ([defns.block]) until the invocation of `callback` returns - such that the return from the invocation of `callback` + ([defns.block]) until the invocation of `cbfn` returns + such that the return from the invocation of `cbfn` strongly happens before ([intro.races]) the destruction of - `callback`. + `cbfn`. - 4. If `callback` is executing on the current thread, then the + 4. If `cbfn` is executing on the current thread, then the destructor shall not block waiting for the return from the - invocation of `callback`. + invocation of `cbfn`. 5. A stoppable callback deregistration shall not block on the completion of the invocation of some other callback registered with the same logical stop state. 6. As a final step, the stoppable callback deregistration shall destroy - the callback function. - + `cbfn`. 4. The `stoppable_token` concept checks for the basic interface of a stop token that is copyable and allows polling to see if stop has been requested and @@ -4367,7 +4364,7 @@ Header `` synopsis [thread.stoptoken.syn] and Class } && copyable<Token> && equality_comparable<Token> && - swappable; + swappable<Token>; template<class Token> concept unstoppable_token = @@ -4379,18 +4376,18 @@ Header `` synopsis [thread.stoptoken.syn] and Class 5. The type `Token` models `stoppable_token` only if: - 1. If an evaluation, `E`, of `t.stop_possible()` evaluates to `false`, then + 1. An evaluation, `E`, of `t.stop_possible()` is `false`, then evaluations of `u.stop_possible()` and `u.stop_requested()` that happen after `E` shall evaluate to `false`. - 2. If an evaluation, `E`, of `t.stop_requested()` evaluates to `true`, then - evaluations of `u.stop_possible()` and `u.stop_requested()` that happens + 2. An evaluation, `E`, of `t.stop_requested()` is `true`, then + evaluations of `u.stop_possible()` and `u.stop_requested()` that happen after `E` shall evaluate to `true`. - 3. For any types `Callback` and `Initializer`, if - stoppable-callback-for<Callback, Token, + 3. For any types `CallbackFn` and `Initializer`, if + stoppable-callback-for<CallbackFn, Token, Initializer> is satisfied, then - stoppable-callback-for<Callback, Token, + stoppable-callback-for<CallbackFn, Token, Initializer> shall be modeled. 4. An object that models `stoppable_token` has at most one associated @@ -4401,10 +4398,10 @@ Header `` synopsis [thread.stoptoken.syn] and Class `t` and `u` are disengaged, `t == u` shall be `true`; otherwise, it shall be `false`. -6. A model of the exposition-only `stoppable-source` concept can be - queried whether stop has been requested (`stop_requested`) and whether stop - is possible (`stop_possible`). It is a factory for associated stop tokens - (`get_token`) and can be explicitly placed into the "stop requested" state +6. An object whose type models the exposition-only `stoppable-source` + concept can be queried whether stop has been requested (`stop_requested`) + and whether stop is possible (`stop_possible`). It is a factory for + associated stop tokens (`get_token`), and a stop request can be made on it (`request_stop`). It maintains a list of registered stop callback invocations that it executes when a stop request is first made. @@ -4458,9 +4455,9 @@ Header `` synopsis [thread.stoptoken.syn] and Class class="wg21note">No constraint is placed on the order in which the callback invocations are executed. `request_stop` shall return `true` if a stop request was made, and `false` otherwise. After a call - to `request_stop` either `stop_possible()` shall be `false` or - `stop_requested()` shall be `true`. - + to `request_stop` either a call to `stop_possible` shall return `false` + or a call to `stop_requested` shall return `true`. + A stop request includes notifying all condition variables of type `condition_variable_any` temporarily registered during an interruptible wait ([thread.condvarany.intwait]). @@ -4489,8 +4486,8 @@ Header `` synopsis [thread.stoptoken.syn] and Class namespace std { class stop_token { public: -
template<class T> - using callback_type = stop_callback<T>;
+
template<class CallbackFn> + using callback_type = stop_callback<CallbackFn>;
// [stoptoken.cons], constructors, copy, and assignment stop_token() noexcept = default; @@ -4841,18 +4838,18 @@ friend void swap(stop_source& x, stop_source& y) noexcept;
 namespace std {
-  template<class Callback>
+  template<class CallbackFn>
   class stop_callback {
   public:
-    using callback_type = Callback;
+    using callback_type = CallbackFn;
 
     // 33.3.5.2, constructors and destructor
-    template<class C>
-      explicit stop_callback(const stop_token& st, C&& cb)
-        noexcept(is_nothrow_constructible_v<Callback, C>);
-    template<class C>
-      explicit stop_callback(stop_token&& st, C&& cb)
-        noexcept(is_nothrow_constructible_v<Callback, C>);
+    template<class CBF>
+      explicit stop_callback(const stop_token& st, CBF&& cbfn)
+        noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
+    template<class CBF>
+      explicit stop_callback(stop_token&& st, CBF&& cbfn)
+        noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
     ~stop_callback();
 
     stop_callback(const stop_callback&) = delete;
@@ -4861,16 +4858,17 @@ namespace std {
     stop_callback& operator=(stop_callback&&) = delete;
 
   private:
-    Callback callback; // exposition only
+    CallbackFn callbackcallback-fn; // exposition only
   };
 
-  template<class Callback>
-    stop_callback(stop_token, Callback) -> stop_callback<Callback>;
+  template<class CallbackFn>
+    stop_callback(stop_token, CallbackFn) -> stop_callback<CallbackFn>;
 }
 
2. *Mandates:* `stop_callback` is instantiated with an argument for the template - parameter `Callback` that satisfies both `invocable` and `destructible`. + parameter CallbackFn that satisfies both `invocable` + and `destructible`.
3. *Preconditions:* `stop_callback` is instantiated with an argument for the @@ -4881,46 +4879,50 @@ namespace std {
-3. *Remarks:* For a type `C`, if - stoppable-callback-for<Callback, stop_token, C> is - satisfied, then stoppable-callback-for<Callback, stop_token, - C> is modeled. The exposition-only `callback` member is the +3. *Remarks:* For a type CBF, if + stoppable-callback-for<CallbackFn, stop_token, CBF> is + satisfied, then stoppable-callback-for<CallbackFn, stop_token, + CBF> is modeled. The exposition-only `callback-fn` member is the associated callback function ([stoptoken.concepts]) of - `stop_callback` objects. + `stop_callback` objects.
#### Constructors and destructor [stopcallback.cons] #### {#spec-stopcallback.cons}
-template<class C>
-explicit stop_callback(const stop_token& st, C&& cb)
-  noexcept(is_nothrow_constructible_v<Callback, C>);
-template<class C>
-explicit stop_callback(stop_token&& st, C&& cb)
-  noexcept(is_nothrow_constructible_v<Callback, C>);
+template<class CBF>
+explicit stop_callback(const stop_token& st, CBF&& cbfn)
+  noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
+template<class CBF>
+explicit stop_callback(stop_token&& st, CBF&& cbfn)
+  noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
 
-1. *Constraints:* `Callback` and `C` satisfy `constructible_from`. +1. *Constraints:* CallbackFn and CBF satisfy + constructible_from<CallbackFn, CBF>.
2. *Preconditions:* `Callback` and `C` model `constructible_from`.
-3. *Effects:* Initializes `callback` with `std::forward(cb)` and - executes a stoppable callback registration ([stoptoken.concepts]). If - `st.stop_requested()` is `true`, then `std::forward(callback)()` - is evaluated in the current thread before the constructor returns. - Otherwise, if `st` has ownership of a stop state, acquires shared ownership - of that stop state and registers the callback with that stop state such that - `std::forward(callback)()` is evaluated by the first call to - `request_stop()` on an associated `stop_source`. If a callback - is registered with `st`'s shared stop state, then `*this` acquires shared +3. *Effects:* Initializes + callbackcallback-fn with + std::forward<CBF>(cbfn) and + executes a stoppable callback registration + ([stoptoken.concepts]). If `st.stop_requested()` is `true`, then + `std::forward<Callback>(callback)()` is evaluated in the current thread + before the constructor returns. Otherwise, if `st` has ownership of a stop + state, acquires shared ownership of that stop state and registers the + callback with that stop state such that + `std::forward<Callback>(callback)()` is evaluated by the first call to + `request_stop()` on an associated `stop_source`. If a callback is + registered with `st`'s shared stop state, then `*this` acquires shared ownership of that stop state.
-4. *Throws:* Any exception thrown by the initialization of callback. +4. *Throws:* Any exception thrown by the initialization of `callback`. 5. *Remarks:* If evaluating `std::forward(callback)()` exits via an exception, then `terminate` is invoked ([except.terminate]). @@ -4963,12 +4965,12 @@ explicit stop_callback(stop_token&& st, C&& cb)
     namespace std {
       class never_stop_token {
-        struct callback { // exposition only
-          explicit callback(never_stop_token, auto&&) noexcept {}
+        struct callback-type { // exposition only
+          explicit callback-type(never_stop_token, auto&&) noexcept {}
         };
       public:
         template<class>
-          using callback_type = callback;
+          using callback_type = callback-type;
 
         static constexpr bool stop_requested() noexcept { return false; }
         static constexpr bool stop_possible() noexcept { return false; }
@@ -4997,8 +4999,8 @@ of Stop tokens [thread.stoptoken].
     namespace std {
       class inplace_stop_token {
       public:
-        template<class CB>
-          using callback_type = inplace_stop_callback<CB>;
+        template<class CallbackFn>
+          using callback_type = inplace_stop_callback<CallbackFn>;
 
         inplace_stop_token() noexcept = default;
         bool operator==(const inplace_stop_token&) const noexcept = default;
@@ -5136,15 +5138,15 @@ added above, as a new subclause of Stop tokens [thread.stoptoken].
 
     
     namespace std {
-      template<class Callback>
+      template<class CallbackFn>
       class inplace_stop_callback {
       public:
-        using callback_type = Callback;
+        using callback_type = CallbackFn;
 
         // [stopcallback.inplace.cons], constructors and destructor
-        template<class C>
-          explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
-            noexcept(is_nothrow_constructible_v<Callback, C>);
+        template<class CBF>
+          explicit inplace_stop_callback(inplace_stop_token st, CBF&& cbfn)
+            noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
         ~inplace_stop_callback();
 
         inplace_stop_callback(inplace_stop_callback&&) = delete;
@@ -5153,26 +5155,26 @@ added above, as a new subclause of Stop tokens [thread.stoptoken].
         inplace_stop_callback& operator=(const inplace_stop_callback&) = delete;
 
       private:
-        Callback stop-callback;      // exposition only
+        CallbackFn callback-fn;      // exposition only
       };
 
-      template<class Callback>
-        inplace_stop_callback(inplace_stop_token, Callback)
-          -> inplace_stop_callback<Callback>;
+      template<class CallbackFn>
+        inplace_stop_callback(inplace_stop_token, CallbackFn)
+          -> inplace_stop_callback<CallbackFn>;
     }
     
1. *Mandates*: `inplace_stop_callback` is instantiated with an argument for the - template parameter `Callback` that satisfies both `invocable` and + template parameter `CallbackFn` that satisfies both `invocable` and `destructible`. -2. *Remarks:* For a type `C`, if - stoppable-callback-for<Callback, inplace_stop_token, - C> is satisfied, then - stoppable-callback-for<Callback, inplace_stop_token, - C> is modeled. The exposition-only `stop-callback` member is +2. *Remarks:* For a type `CBF`, if + stoppable-callback-for<CallbackFn, inplace_stop_token, + CBF> is satisfied, then + stoppable-callback-for<CallbackFn, inplace_stop_token, + CBF> is modeled. The exposition-only `callback-fn` member is the associated callback function ([stoptoken.concepts]) of - `inplace_stop_callback` objects. + `inplace_stop_callback` objects. Implementations are not permitted to use additional storage, such as dynamic memory, to store the state necessary for an @@ -5183,22 +5185,22 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons}
-template<class C>
-  explicit inplace_stop_callback(inplace_stop_token st, C&& cb)
-    noexcept(is_nothrow_constructible_v<Callback, C>);
+template<class CBF>
+  explicit inplace_stop_callback(inplace_stop_token st, CBF&& cbfn)
+    noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
 
-1. *Constraints*: `constructible_from` is satisfied. +1. *Constraints*: `constructible_from` is satisfied. -2. *Effects*: Initializes `stop-callback` with - `std::forward(cb)` and executes a stoppable callback registration +2. *Effects*: Initializes `callback-fn` with + `std::forward(cbfn)` and executes a stoppable callback registration ([stoptoken.concepts]).
 ~inplace_stop_callback();
 
-6. *Effects*: Executes a stoppable callback deregistration +3. *Effects*: Executes a stoppable callback deregistration ([stoptoken.concepts]).
@@ -6355,9 +6357,10 @@ namespace std::execution { constexpr auto completion-domain(const Sndr& sndr) noexcept; - 1. *Effects:* Let COMPL-DOMAIN(T) be the type of the + 1. Let COMPL-DOMAIN(T) be the type of the expression `get_domain(get_completion_scheduler(get_env(sndr)))`. - If COMPL-DOMAIN(set_value_t), + + 2. *Effects:* If COMPL-DOMAIN(set_value_t), COMPL-DOMAIN(set_error_t), and COMPL-DOMAIN(set_stopped_t) all share a common type [meta.trans.other] (ignoring those types that are ill-formed), From d68eecabc0adaba267e93887151f524b4d041e27 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 17 Apr 2024 12:09:58 -0700 Subject: [PATCH 55/89] LWG feedback from 2024-04-17 --- execution.bs | 91 +++++++++++++++++++++++++++------------------------- 1 file changed, 47 insertions(+), 44 deletions(-) diff --git a/execution.bs b/execution.bs index f4c6b78..50e7bd3 100644 --- a/execution.bs +++ b/execution.bs @@ -4135,7 +4135,8 @@ namespace std { respectively.
The last remaining owner of the stop state automatically releases the resources associated with the stop state. -3. A stoppable_token can be passed to an operation +3. An object of a type that models + stoppable_token can be passed to an operation whichthat can either
@@ -4146,15 +4147,15 @@ namespace std { template whichthat will be called in the event that a stop request is made.
- A stop request made via a `stop_source`an object that models - `stoppable-source` will be visible to all associated + A stop request made via a `stop_source`an object whose type + models `stoppable-source` will be visible to all associated stoppable_token and `stop_source` - `stoppable-source` objects. Once a stop request has been - made it cannot be withdrawn (a subsequent stop request has no effect). + `stoppable-source` objects. Once a stop request has been made + it cannot be withdrawn (a subsequent stop request has no effect). 4. Callbacks registered via a `stop_callback` objectan object - that models `stoppable-callback-for` are called when a stop - request is first made by any associated `stop_source` + whose type models `stoppable-callback-for` are called when a + stop request is first made by any associated `stop_source` `stoppable-source` object. The following paragraph is moved to the specification of @@ -4177,10 +4178,11 @@ the new `stoppable-source` concept. The last remaining owner of the stop state automatically releases the resources associated with the stop state. -6. The types `inplace_stop_source` and `inplace_stop_token` and the class - template `inplace_stop_callback` does no dynamic memory allocation of the - stop state. They are for use when the lifetimes of - the associated token and callback objects are known to nest within the +6. An object of type `inplace_stop_source` is the sole owner of its stop state. + An object of type `inplace_stop_token` or of a specialization of the class + template `inplace_stop_callback` does not participate in ownership of its + associated stop state. They are for use when all uses + of the associated token and callback objects are known to nest within the lifetime of the `inplace_stop_source` object.
@@ -4233,13 +4235,13 @@ namespace std { template<class CallbackFn> class inplace_stop_callback; + Do we need the `::template` here? template<class T, class CallbackFn> using stop_callback_for_t = T::template callback_type<CallbackFn>; } - Insert the following subclause as a new subclause between Header `` synopsis [thread.stoptoken.syn] and Class `stop_token` [stoptoken]. @@ -4248,13 +4250,8 @@ Header `` synopsis [thread.stoptoken.syn] and Class ### Stop token concepts [stoptoken.concepts] ### {#spec-stoptoken.concepts} -1. For a stop token type `Token` and a type `CallbackFn` such that - invocable<CallbackFn> is `true`, if the type - `stop_callback_for_t` is valid, it denotes the type of a - stop callback to use when registering a callback invocation to be executed - if a stop request is made on the `stoppable_token`'s associated stop source. - The exposition-only `stoppable-callback-for` concept checks for a - callback compatible with a given stop token type. +1. The exposition-only `stoppable-callback-for` concept checks for a + callback compatible with a given `Token` type.
     template<class CallbackFn, class Token, class Initializer = CallbackFn>
@@ -4266,9 +4263,9 @@ Header `` synopsis [thread.stoptoken.syn] and Class
     
2. Let `t` and `u` be distinct, valid objects of type `Token` that reference the - same logical stop state; let `init` be an object of type - `Initializer`; and let `SCB` denote the type `stop_callback_for_t`. + same logical stop state; let `init` be an expression such that + `same_as` is `true`; and let `SCB` denote the + type `stop_callback_for_t`. 3. The concept stoppable-callback-for<CallbackFn, Token, Initializer> is modeled only if: @@ -4317,11 +4314,12 @@ Header `` synopsis [thread.stoptoken.syn] and Class initialization of `cbfn`. 3. Destruction of `scb` shall execute a stoppable callback - deregistration as follows: + deregistration
as follows (in order): 1. If the constructor of `scb` did not register a callback invocation with `t`'s stop state, then the stoppable callback - deregistration shall have no effect. + deregistration shall have no effect other than destroying `cbfn` + if it was constructed. 2. Otherwise, the invocation of `cbfn` shall be removed from the associated stop state. @@ -4341,13 +4339,13 @@ Header `` synopsis [thread.stoptoken.syn] and Class of the invocation of some other callback registered with the same logical stop state. - 6. As a final step, the stoppable callback deregistration shall destroy + 6. The stoppable callback deregistration shall destroy `cbfn`. 4. The `stoppable_token` concept checks for the basic interface of a stop token that is copyable and allows polling to see if stop has been requested and also whether a stop request is possible. The `unstoppable_token` concept - checks for a stop token type that does not allow stopping. + checks for a `stoppable_token` type that does not allow stopping.
     template<template<class> class>
@@ -4374,31 +4372,36 @@ Header `` synopsis [thread.stoptoken.syn] and Class
         };
     
-5. The type `Token` models `stoppable_token` only if: +5. An object whose type models `stoppable_token` has at most one associated + logical stop state. A `stoppable_token` object with no associated stop + state is said to be disengaged. + +6. Let `SP` be an evaluation of `t.stop_possible()` that is `false`, and let + `SR` be an evaluation of `t.stop_requested()` that is `true`. + +7. The type `Token` models `stoppable_token` only if: - 1. An evaluation, `E`, of `t.stop_possible()` is `false`, then - evaluations of `u.stop_possible()` and `u.stop_requested()` that happen - after `E` shall evaluate to `false`. + 1. Any evaluation of `u.stop_possible()` or `u.stop_requested()` + that happens after ([intro.races]) `SP` is `false`. - 2. An evaluation, `E`, of `t.stop_requested()` is `true`, then - evaluations of `u.stop_possible()` and `u.stop_requested()` that happen - after `E` shall evaluate to `true`. + 2. Any evaluation of `u.stop_possible()` or `u.stop_requested()` + that happens after `SR` is `true`. - 3. For any types `CallbackFn` and `Initializer`, if + 3. For any types `CallbackFn` and `Initializer` such that stoppable-callback-for<CallbackFn, Token, - Initializer> is satisfied, then + Initializer>
is satisfied, stoppable-callback-for<CallbackFn, Token, - Initializer> shall be modeled. + Initializer>
is modeled. + + 4. If `t` is disengaged, evaluations of `t.stop_possible()` and + `t.stop_requested()` are `false`. + + 5. If `t` and `u` reference the same stop state, or if both `t` and `u` are + disengaged, `t == u` is `true`; otherwise, it is `false`. - 4. An object that models `stoppable_token` has at most one associated - logical stop state. A `stoppable_token` object with no associated stop - state is said to be disengaged. For a disengaged - `stoppable_token` object, `stop_possible` and `stop_requested` shall - return `false`. If `t` and `u` reference the same stop state, or if both - `t` and `u` are disengaged, `t == u` shall be `true`; otherwise, it - shall be `false`. + -6. An object whose type models the exposition-only `stoppable-source` +8. An object whose type models the exposition-only `stoppable-source` concept can be queried whether stop has been requested (`stop_requested`) and whether stop is possible (`stop_possible`). It is a factory for associated stop tokens (`get_token`), and a stop request can be made on it From 7daa09f77a390d546ff5748be0ced6ca09acdbde Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 1 May 2024 14:59:23 -0700 Subject: [PATCH 56/89] LWG feedback from the 2024-05-01 telecon --- execution.bs | 165 +++++++++++++++++++++++++-------------------------- 1 file changed, 81 insertions(+), 84 deletions(-) diff --git a/execution.bs b/execution.bs index 50e7bd3..ad586c7 100644 --- a/execution.bs +++ b/execution.bs @@ -4278,69 +4278,67 @@ Header `` synopsis [thread.stoptoken.syn] and Class 2. An object of type `SCB` has an associated callback function of type `CallbackFn`. Let `scb` be an object of type `SCB` - and let `cbfn` denote `scb`'s associated callback function. + and let `callback_fn` denote `scb`'s associated callback function. Direct-non-list-initializing `scb` from arguments `t` and `init` shall execute a stoppable callback registration as follows: 1. If `t.stop_possible()` is `true`: - 1. `cbfn` shall be direct-initialized with `init`. + 1. `callback_fn` shall be direct-initialized with `init`. 2. Construction of `scb` shall only throw exceptions thrown by the - initialization of `cbfn` from `init`. + initialization of `callback_fn` from `init`. - 3. The callback invocation - std::forward<CallbackFn>(cbfn)() shall - be registered with `t`'s associated stop state as follows: + 3. The callback invocation `std::forward(callback_fn)()` + shall be registered with `t`'s associated stop state as follows: 1. If `t.stop_requested()` evaluates to `false` at the time of registration, the callback invocation is added to the stop state's list of callbacks such that - std::forward<CallbackFn>(cbfn)() is - evaluated if a stop request is made on the stop state. + `std::forward(callback_fn)()` is evaluated if a + stop request is made on the stop state. - 2. Otherwise, - std::forward<CallbackFn>(cbfn)() - shall be immediately evaluated on the thread executing - `scb`'s constructor, and the callback invocation shall not be - added to the list of callback invocations. + 2. Otherwise, `std::forward(callback_fn)()` shall be + immediately evaluated on the thread executing `scb`'s + constructor, and the callback invocation shall not be added + to the list of callback invocations. 4. If the callback invocation was added to stop state's list of callbacks, `scb` shall be associated with the stop state. 2. If `t.stop_possible()` is `false`, there is no requirement that the initialization of `scb` causes the - initialization of `cbfn`. + initialization of `callback_fn`. 3. Destruction of `scb` shall execute a stoppable callback deregistration as follows (in order): 1. If the constructor of `scb` did not register a callback invocation with `t`'s stop state, then the stoppable callback - deregistration shall have no effect other than destroying `cbfn` + deregistration shall have no effect other than destroying `callback_fn` if it was constructed. - 2. Otherwise, the invocation of `cbfn` shall be removed from + 2. Otherwise, the invocation of `callback_fn` shall be removed from the associated stop state. - 3. If `cbfn` is concurrently executing on another thread + 3. If `callback_fn` is concurrently executing on another thread then the stoppable callback deregistration shall block - ([defns.block]) until the invocation of `cbfn` returns - such that the return from the invocation of `cbfn` + ([defns.block]) until the invocation of `callback_fn` returns + such that the return from the invocation of `callback_fn` strongly happens before ([intro.races]) the destruction of - `cbfn`. + `callback_fn`. - 4. If `cbfn` is executing on the current thread, then the + 4. If `callback_fn` is executing on the current thread, then the destructor shall not block waiting for the return from the - invocation of `cbfn`. + invocation of `callback_fn`. 5. A stoppable callback deregistration shall not block on the completion of the invocation of some other callback registered with the same logical stop state. 6. The stoppable callback deregistration shall destroy - `cbfn`. + `callback_fn`. 4. The `stoppable_token` concept checks for the basic interface of a stop token that is copyable and allows polling to see if stop has been requested and @@ -4399,8 +4397,6 @@ Header `` synopsis [thread.stoptoken.syn] and Class 5. If `t` and `u` reference the same stop state, or if both `t` and `u` are disengaged, `t == u` is `true`; otherwise, it is `false`. - - 8. An object whose type models the exposition-only `stoppable-source` concept can be queried whether stop has been requested (`stop_requested`) and whether stop is possible (`stop_possible`). It is a factory for @@ -4420,15 +4416,15 @@ Header `` synopsis [thread.stoptoken.syn] and Class }; - 1. A `stoppable-source` object has at most one associated logical - stop state. A `stoppable-source` object with no associated stop - state is said to be disengaged. For a disengaged - `stoppable-source` object, `stop_possible` and `stop_requested` - shall return `false`. + 1. An object whose type models `stoppable-source` has at most one + associated logical stop state. If it has no associated stop state, it is + said to be disengaged. Let `s` be an object whose type models + `stoppable-source` and that is disengaged. `s.stop_possible()` + and `s.stop_requested()` shall return `false`. - 2. A disengaged `stoppable-source` object shall return a disengaged - stop token from `get_token()`. Otherwise, `get_token()` shall return a - stop token that is associated with the stop state of the source. + 2. Let `t` be an object whose type models `stoppable-source`. If `t` is + disengaged, `t.get_token()` shall return a disengaged stop token; otherwise, + it shall return a stop token that is associated with the stop state of `t`. The following paragraph is moved from the introduction, with minor modifications (underlined in green). @@ -4519,7 +4515,7 @@ namespace std {
1. `stop-state` refers to the `stop_token`'s associated stop state. A - `stop_token` object is disengaged when `stop-state` is null.
+ `stop_token` object is disengaged when `stop-state` is empty. @@ -4582,7 +4578,7 @@ void swap(stop_token& rhs) noexcept; 1. *Effects:* Exchanges the values of `*this` and `rhs`. Equivalent to: - std::swap(stop-state, rhs.stop-state). + stop-state.swap(rhs.stop-state).
 [[nodiscard]] bool stop_requested() const noexcept;
@@ -4634,11 +4630,11 @@ friend void swap(stop_token& x, stop_token& y) noexcept;
 
 #### General [stopsource.general] #### {#spec-stopsource.general}
 
-1. The class `stop_source` implements the semantics of making a stop
+1. The class `stop_source` implements the semantics of making a stop
     request. A stop request made on a `stop_source` object is visible to all
     associated `stop_source` and `stop_token` ([thread.stoptoken]) objects. Once
     a stop request has been made it cannot be withdrawn (a subsequent stop
-    request has no effect)models `stoppable-source`.
+    request has no effect).
 
 
 namespace std {
@@ -4682,9 +4678,10 @@ namespace std {
 
 
1. `stop-state` refers to the `stop_source`'s associated stop state. A - `stop_source` object is disengaged when `stop-state` is null. + `stop_source` object is disengaged when `stop-state` is empty. -2. `stop_source` models `copyable`, `equality_comparable`, and `swappable`. +2. `stop_source` models `stoppable-source`, `copyable`, + `equality_comparable`, and `swappable`.
@@ -4755,29 +4752,29 @@ stop_source& operator=(stop_source&& rhs) noexcept; void swap(stop_source& rhs) noexcept;
-12. *Effects:* Exchanges the values of `*this` and `rhs`Equivalent to: - std::swap(stop-state, rhs.stop-state). +1. *Effects:* Exchanges the values of `*this` and `rhs`Equivalent to: + stop-state.swap(rhs.stop-state).
 [[nodiscard]] stop_token get_token() const noexcept;
 
-1. *Returns:* `stop_token()` if `stop_possible()` is `false`; otherwise a new - associated `stop_token` object; *i.e.*, its `stop-state` pointer - is equal to the `stop-state` pointer of `*this`. +2. *Returns:* `stop_token()` if `stop_possible()` is `false`; otherwise a new + associated `stop_token` object; *i.e.*, its `stop-state` member + is equal to the `stop-state` member of `*this`.
 [[nodiscard]] bool stop_possible() const noexcept;
 
-2. *Returns:* `true` if `*this` has ownership of a stop state; otherwise, +3. *Returns:* `true` if `*this` has ownership of a stop state; otherwise, `false`stop-state != nullptr.
 [[nodiscard]] bool stop_requested() const noexcept;
 
-3. *Returns:* `true` if `*this` has ownership +4. *Returns:* `true` if `*this` has ownership of`stop-state` refers to a stop state that has received a stop request; otherwise, `false`. @@ -4786,7 +4783,7 @@ bool request_stop() noexcept;
-4. *Effects:* Executes a stop request operation ([stoptoken.concepts]) on the +5. *Effects:* Executes a stop request operation ([stoptoken.concepts]) on the associated stop state, if any.
@@ -4847,12 +4844,12 @@ namespace std { using callback_type = CallbackFn; // 33.3.5.2, constructors and destructor - template<class CBF> - explicit stop_callback(const stop_token& st, CBF&& cbfn) - noexcept(is_nothrow_constructible_v<CallbackFn, CBF>); - template<class CBF> - explicit stop_callback(stop_token&& st, CBF&& cbfn) - noexcept(is_nothrow_constructible_v<CallbackFn, CBF>); + template<class CInitializer> + explicit stop_callback(const stop_token& st, CInitializer&& cbinit) + noexcept(is_nothrow_constructible_v<CallbackFn, CInitializer>); + template<class CInitializer> + explicit stop_callback(stop_token&& st, CInitializer&& cbinit) + noexcept(is_nothrow_constructible_v<CallbackFn, CInitializer>); ~stop_callback(); stop_callback(const stop_callback&) = delete; @@ -4882,10 +4879,10 @@ namespace std {
-3. *Remarks:* For a type CBF, if - stoppable-callback-for<CallbackFn, stop_token, CBF> is +3. *Remarks:* For a type Initializer, if + stoppable-callback-for<CallbackFn, stop_token, Initializer> is satisfied, then stoppable-callback-for<CallbackFn, stop_token, - CBF> is modeled. The exposition-only `callback-fn` member is the + Initializer> is modeled. The exposition-only `callback-fn` member is the associated callback function ([stoptoken.concepts]) of `stop_callback` objects. @@ -4894,16 +4891,16 @@ namespace std { #### Constructors and destructor [stopcallback.cons] #### {#spec-stopcallback.cons}
-template<class CBF>
-explicit stop_callback(const stop_token& st, CBF&& cbfn)
-  noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
-template<class CBF>
-explicit stop_callback(stop_token&& st, CBF&& cbfn)
-  noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
+template<class CInitializer>
+explicit stop_callback(const stop_token& st, CInitializer&& cbinit)
+  noexcept(is_nothrow_constructible_v<CallbackFn, CInitializer>);
+template<class CInitializer>
+explicit stop_callback(stop_token&& st, CInitializer&& cbinit)
+  noexcept(is_nothrow_constructible_v<CallbackFn, CInitializer>);
 
-1. *Constraints:* CallbackFn and CBF satisfy - constructible_from<CallbackFn, CBF>. +1. *Constraints:* CallbackFn and CInitializer satisfy + constructible_from<CallbackFn, CInitializer>.
2. *Preconditions:* `Callback` and `C` model `constructible_from`. @@ -4912,7 +4909,7 @@ explicit stop_callback(stop_token&& st, CBF&& cbfn) 3. *Effects:* Initializes callbackcallback-fn with - std::forward<CBF>(cbfn) and + std::forward<CInitializer>(cbinit) and executes a stoppable callback registration ([stoptoken.concepts]). If `st.stop_requested()` is `true`, then `std::forward<Callback>(callback)()` is evaluated in the current thread @@ -4944,12 +4941,13 @@ explicit stop_callback(stop_token&& st, CBF&& cbfn) If `callback` is executing on the current thread, then the destructor does not block ([defns.block]) waiting for the return from the invocation of `callback`. Releases Executes a stoppable callback deregistration - ([stoptoken.concepts]), and releases ownership of the stop state, if + ([stoptoken.concepts]) and releases ownership of the stop state, if any. -
+ + Insert a new subclause, Class `never_stop_token` [stoptoken.never], after subclause Class template `stop_callback` @@ -5147,9 +5145,9 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. using callback_type = CallbackFn; // [stopcallback.inplace.cons], constructors and destructor - template<class CBF> - explicit inplace_stop_callback(inplace_stop_token st, CBF&& cbfn) - noexcept(is_nothrow_constructible_v<CallbackFn, CBF>); + template<class Initializer> + explicit inplace_stop_callback(inplace_stop_token st, Initializer&& init) + noexcept(is_nothrow_constructible_v<CallbackFn, Initializer>); ~inplace_stop_callback(); inplace_stop_callback(inplace_stop_callback&&) = delete; @@ -5171,32 +5169,31 @@ added above, as a new subclause of Stop tokens [thread.stoptoken]. template parameter `CallbackFn` that satisfies both `invocable` and `destructible`. -2. *Remarks:* For a type `CBF`, if +2. *Remarks:* For a type `Initializer`, if stoppable-callback-for<CallbackFn, inplace_stop_token, - CBF> is satisfied, then + Initializer> is satisfied, then stoppable-callback-for<CallbackFn, inplace_stop_token, - CBF> is modeled. The exposition-only `callback-fn` member is - the associated callback function ([stoptoken.concepts]) of + Initializer> is modeled. The exposition-only `callback-fn` + member is the associated callback function ([stoptoken.concepts]) of `inplace_stop_callback` objects. - Implementations are not permitted to use additional storage, such - as dynamic memory, to store the state necessary for an - `inplace_stop_callback`'s association with an `inplace_stop_source` object - or to register the callback invocation with the associated - `inplace_stop_source` object. + Implementations are not permitted to use additional storage, such as dynamic + memory, to store the state necessary for an `inplace_stop_callback`'s + association with an `inplace_stop_source` object or to register the callback + invocation with the associated `inplace_stop_source` object. #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons}
-template<class CBF>
-  explicit inplace_stop_callback(inplace_stop_token st, CBF&& cbfn)
-    noexcept(is_nothrow_constructible_v<CallbackFn, CBF>);
+template<class Initializer>
+  explicit inplace_stop_callback(inplace_stop_token st, Initializer&& init)
+    noexcept(is_nothrow_constructible_v<CallbackFn, Initializer>);
 
-1. *Constraints*: `constructible_from` is satisfied. +1. *Constraints*: `constructible_from` is satisfied. 2. *Effects*: Initializes `callback-fn` with - `std::forward(cbfn)` and executes a stoppable callback registration + `std::forward(init)` and executes a stoppable callback registration ([stoptoken.concepts]).

From 16001062afcd4ca7ee5647feb81191959f01b881 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Wed, 8 May 2024 10:53:20 -0700
Subject: [PATCH 57/89] changes requested during the 2024-05-08 LWG wording
 review telecon

---
 execution.bs | 152 +++++++++++++++++++++++----------------------------
 1 file changed, 67 insertions(+), 85 deletions(-)

diff --git a/execution.bs b/execution.bs
index ad586c7..73484ef 100644
--- a/execution.bs
+++ b/execution.bs
@@ -4976,7 +4976,7 @@ explicit stop_callback(stop_token&& st, CInitializer&& 
@@ -5003,8 +5003,8 @@ of Stop tokens [thread.stoptoken].
         template<class CallbackFn>
           using callback_type = inplace_stop_callback<CallbackFn>;
 
-        inplace_stop_token() noexcept = default;
-        bool operator==(const inplace_stop_token&) const noexcept = default;
+        inplace_stop_token() = default;
+        bool operator==(const inplace_stop_token&) const = default;
 
         // [stoptoken.inplace.mem], member functions
         bool stop_requested() const noexcept;
@@ -5061,18 +5061,14 @@ of Stop tokens [thread.stoptoken].
 
 #### General [stopsource.inplace.general] #### {#spec-stopsource.inplace.general}
 
-1. The class `inplace_stop_source` models `stoppable-source`. Unlike
-    `stop_source`, `inplace_stop_source` does not require dynamic allocation or
-    reference counting of a shared stop state. Instead, it requires that all
-    uses of associated `inplace_stop_token` and `inplace_stop_callback`
-    objects happen before the `inplace_stop_source` is destroyed.
+1. The class `inplace_stop_source` models `stoppable-source`.
 
     
     namespace std {
       class inplace_stop_source {
       public:
         // [stopsource.inplace.cons], constructors, copy, and assignment
-        inplace_stop_source() noexcept;
+        constexpr inplace_stop_source() noexcept;
 
         inplace_stop_source(inplace_stop_source&&) = delete;
         inplace_stop_source(const inplace_stop_source&) = delete;
@@ -5081,7 +5077,7 @@ of Stop tokens [thread.stoptoken].
         ~inplace_stop_source();
 
         //[stopsource.inplace.mem], stop handling
-        inplace_stop_token get_token() const noexcept;
+        constexpr inplace_stop_token get_token() const noexcept;
         static constexpr bool stop_possible() noexcept { return true; }
         bool stop_requested() const noexcept;
         bool request_stop() noexcept;
@@ -5092,7 +5088,7 @@ of Stop tokens [thread.stoptoken].
 #### Constructors, copy, and assignment [stopsource.inplace.cons] #### {#spec-stopsource.inplace.cons}
 
 
-inplace_stop_source() noexcept;
+constexpr inplace_stop_source() noexcept;
 
1. *Effects*: Initializes a new stop state inside `*this`. @@ -5102,10 +5098,11 @@ inplace_stop_source() noexcept; #### Members [stopsource.inplace.mem] #### {#spec-stopsource.inplace.mem}
-inplace_stop_token get_token() const noexcept;
+constexpr inplace_stop_token get_token() const noexcept;
 
-1. *Returns*: A new associated `inplace_stop_token` object. +1. *Returns*: A new associated `inplace_stop_token` object. The `inplace_stop_token` + object's `stop-source` member is equal to `this`.
 bool stop_requested() const noexcept;
@@ -5135,52 +5132,43 @@ added above, as a new subclause of Stop tokens [thread.stoptoken].
 
 #### General [stopcallback.inplace.general] #### {#spec-stopcallback.inplace.general}
 
-1.
-
-    
-    namespace std {
-      template<class CallbackFn>
-      class inplace_stop_callback {
-      public:
-        using callback_type = CallbackFn;
+
+namespace std {
+  template<class CallbackFn>
+  class inplace_stop_callback {
+  public:
+    using callback_type = CallbackFn;
 
-        // [stopcallback.inplace.cons], constructors and destructor
-        template<class Initializer>
-          explicit inplace_stop_callback(inplace_stop_token st, Initializer&& init)
-            noexcept(is_nothrow_constructible_v<CallbackFn, Initializer>);
-        ~inplace_stop_callback();
+    // [stopcallback.inplace.cons], constructors and destructor
+    template<class Initializer>
+      explicit inplace_stop_callback(inplace_stop_token st, Initializer&& init)
+        noexcept(is_nothrow_constructible_v<CallbackFn, Initializer>);
+    ~inplace_stop_callback();
 
-        inplace_stop_callback(inplace_stop_callback&&) = delete;
-        inplace_stop_callback(const inplace_stop_callback&) = delete;
-        inplace_stop_callback& operator=(inplace_stop_callback&&) = delete;
-        inplace_stop_callback& operator=(const inplace_stop_callback&) = delete;
+    inplace_stop_callback(inplace_stop_callback&&) = delete;
+    inplace_stop_callback(const inplace_stop_callback&) = delete;
+    inplace_stop_callback& operator=(inplace_stop_callback&&) = delete;
+    inplace_stop_callback& operator=(const inplace_stop_callback&) = delete;
 
-      private:
-        CallbackFn callback-fn;      // exposition only
-      };
+  private:
+    CallbackFn callback-fn;      // exposition only
+  };
 
-      template<class CallbackFn>
-        inplace_stop_callback(inplace_stop_token, CallbackFn)
-          -> inplace_stop_callback<CallbackFn>;
-    }
-    
+ template<class CallbackFn> + inplace_stop_callback(inplace_stop_token, CallbackFn) + -> inplace_stop_callback<CallbackFn>; +} +
-1. *Mandates*: `inplace_stop_callback` is instantiated with an argument for the - template parameter `CallbackFn` that satisfies both `invocable` and - `destructible`. +1. *Mandates*: `CallbackFn` satisfies both `invocable` and `destructible`. 2. *Remarks:* For a type `Initializer`, if stoppable-callback-for<CallbackFn, inplace_stop_token, Initializer> is satisfied, then stoppable-callback-for<CallbackFn, inplace_stop_token, - Initializer> is modeled. The exposition-only `callback-fn` - member is the associated callback function ([stoptoken.concepts]) of - `inplace_stop_callback` objects. - - Implementations are not permitted to use additional storage, such as dynamic - memory, to store the state necessary for an `inplace_stop_callback`'s - association with an `inplace_stop_source` object or to register the callback - invocation with the associated `inplace_stop_source` object. + Initializer> is modeled. For an `inplace_stop_callback` + object, the exposition-only `callback-fn` member is its associated + callback function ([stoptoken.concepts]). #### Constructors and destructor [stopcallback.inplace.cons] #### {#spec-stopcallback.inplace.cons} @@ -5231,11 +5219,8 @@ template<class Initializer> [exec.execute]One-way execution -3. [Note: A large number of execution control primitives are - customization point objects. For an object one might define multiple types of - customization point objects, for which different rules apply. Table 2 shows - the types of customization point objects used in the execution control - library: +3. Table 2 shows the types of customization point objects + [customization.point.object] used in the execution control library: @@ -5247,7 +5232,7 @@ template<class Initializer> - + @@ -5259,9 +5244,9 @@ template<class Initializer> @@ -5270,17 +5255,15 @@ template<class Initializer>
Table N+1: Types of customization point objects in the execution control library [tab:execution.cpos]
core provide core execution functionality, and connection between core components`connect`, `start`, `execute`e.g., `connect`, `start`, `execute`
completion functionsallow the specialization of the provided sender algorithms
    -
  • sender factories (`schedule`, `just`, `read`, ...)
  • -
  • sender adaptors (`transfer`, `then`, `let_value`, ...)
  • -
  • sender consumers (`start_detached`, `sync_wait`)
  • +
  • sender factories (e.g., `schedule`, `just`, `read`)
  • +
  • sender adaptors (e.g., `transfer`, `then`, `let_value`)
  • +
  • sender consumers (e.g., `start_detached`, `sync_wait`)
allow querying different properties of objects
    -
  • general queries (`get_allocator`, `get_stop_token`, ...)
  • -
  • environment queries (`get_scheduler`, `get_delegatee_scheduler`, ...)
  • -
  • scheduler queries (`get_forward_progress_guarantee`, `execute_may_block_caller`, ...)
  • -
  • sender attribute queries (`get_completion_scheduler`)
  • +
  • general queries (e.g., `get_allocator`, `get_stop_token`)
  • +
  • environment queries (e.g., `get_scheduler`, `get_delegatee_scheduler`)
  • +
  • scheduler queries (e.g., `get_forward_progress_guarantee`, `execute_may_block_caller`)
  • +
  • sender attribute queries (e.g., `get_completion_scheduler`)
--- end note] - 4. This clause makes use of the following exposition-only entities: 1. For a subexpression expr, let @@ -5293,16 +5276,16 @@ template<class Initializer> 2.
         namespace std {
           template<class T>
-            concept movable-value =
+            concept movable-value = // exposition only
               move_constructible<decay_t<T>> &&
               constructible_from<decay_t<T>, T> &&
-              (!is_array_v<remove_cvref_t<T>>);
+              (!is_array_v<remove_reference_t<T>>);
         }
         
3. For function types `F1` and `F2` denoting `R1(Args1...)` and `R2(Args2...)` respectively, MATCHING-SIG(F1, F2) is - `true` if and only if `same_as` is + `true` if and only if `same_as` is `true`. 4. For a subexpression `err`, let `Err` be `decltype((err))` and let @@ -5310,10 +5293,10 @@ template<class Initializer> 1. `err` if `decay_t` denotes the type `exception_ptr`. - - *Mandates:* `err != exception_ptr()` is `true` + - *Mandates:* `err != exception_ptr()` is `true`. 2. Otherwise, `make_exception_ptr(system_error(err))` if `decay_t` - denotes the type `error_code`, + denotes the type `error_code`. 3. Otherwise, `make_exception_ptr(err)`. @@ -5326,27 +5309,25 @@ template<class Initializer> query object. A query is an invocation of a query object with a queryable object as its first argument and a (possibly empty) set of additional - arguments. The result of a query expression is valid as long as the - queryable object is valid. A query imposes syntactic - and semantic requirements on its invocations. + arguments. A query imposes syntactic and semantic + requirements on its invocations. -2. Given a subexpression `env` that refers to a queryable object `o`, a query - object `q`, and a (possibly empty) pack of subexpressions - `args`, the expression q(env, args...) is equal to - ([concepts.equality]) the expression q(c, args...) where - `c` is a `const` lvalue reference to `o`. +2. Let `q` be a query object, let `args` be a (possibly empty) pack of + subexpressions, let `env` be a subexpression that refers to a queryable + object `o` of type `O`, and let `cenv` be a subexpression refering to `o` + such that `decltype((cenv))` is `const O&`. The expression `q(env, args...)` + is equal to ([concepts.equality]) the expression `q(cenv, args...)`. 3. The type of a query expression can not be `void`. -4. The expression q(env, args...) is equality-preserving - ([concepts.equality]) and does not modify the function object or the - arguments. +4. The expression `q(env, args...)` is equality-preserving + ([concepts.equality]) and does not modify the query object or the arguments. -5. If the expression env.query(q, args...) is well-formed, - then it is expression-equivalent to q(env, args...). +5. If the expression `env.query(q, args...)` is well-formed, then it is + expression-equivalent to `q(env, args...)`. -6. Unless otherwise specified, the value returned by the expression - q(env, args...) is valid as long as `env` is valid. +6. Unless otherwise specified, the result of a query is valid as long as the + queryable object is valid. ### `queryable` concept [exec.queryable.concept] ### {#spec-execution.queryable.concept} @@ -9751,7 +9732,8 @@ void finish(); }
-3. call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value) +3. template<class Value>
+ call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value)
- Effects: equivalent to: From ac96bcd12f569d4f30375290d84d52daf48c0814 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 16 May 2024 10:39:43 -0700 Subject: [PATCH 58/89] apply wording changes requested by LWG on 2024-05-15 --- execution.bs | 243 ++++++++++++++++++++++++++------------------------- 1 file changed, 125 insertions(+), 118 deletions(-) diff --git a/execution.bs b/execution.bs index 73484ef..089a9af 100644 --- a/execution.bs +++ b/execution.bs @@ -609,7 +609,7 @@ The sender/receiver-based Sudoku solver can be found [here](https://github.com/kirkshoop/libunifex/blob/sudoku/examples/sudoku.cpp). Some things that are worth noting about Kirk's solution: -1. Although it schedules asychronous work onto a thread pool, and each unit of +1. Although it schedules asynchronous work onto a thread pool, and each unit of work will schedule more work, its use of structured concurrency patterns make reference counting unnecessary. The solution does not make use of `shared_ptr`. @@ -3900,21 +3900,20 @@ struct my_receiver {
The only exception to this is the customization of queries. There is a need to -build queryable adaptors that can forward and open and unknowable set of queries +build queryable adaptors that can forward an open and unknowable set of queries to some wrapped object. This is done by defining a member function named `query` in the adaptor type that takes the query CPO object as its first (and usually only) argument. A queryable adaptor might look like this:
-template <class Query, class Queryable, class... Args>
+template<class Query, class Queryable, class... Args>
 concept query_for =
-  execution::queryable<Queryable> &&
   requires (const Queryable& o, Args&&... args) {
     o.query(Query(), (Args&&) args...);
   };
 
 template<class Allocator = std::allocator<>,
-         execution::queryable Base = execution::empty_env>
+        class Base = execution::empty_env>
 struct with_allocator {
   Allocator alloc{};
   Base base{};
@@ -4946,9 +4945,6 @@ explicit stop_callback(stop_token&& st, CInitializer&& 
 
-
-
-
 Insert a new subclause, Class `never_stop_token`
 [stoptoken.never], after subclause Class template `stop_callback`
 [stopcallback], as a new subclause of Stop tokens
@@ -5329,23 +5325,22 @@ template<class Initializer>
 6. Unless otherwise specified, the result of a query is valid as long as the
     queryable object is valid.
 
-### `queryable` concept [exec.queryable.concept] ### {#spec-execution.queryable.concept}
+### `queryable` concept [exec.queryable.concept] ### {#spec-execution.queryable.concept}
 
     
     namespace std {
       template<class T>
-        concept queryable = destructible<T>;
+        concept queryable = destructible<T>; // exposition only
     }
     
-1. The `queryable` concept specifies the constraints on the types of queryable - objects. +1. The exposition-only `queryable` concept specifies the constraints on + the types of queryable objects. -2. Let `env` be an object of type `Env`. The type `Env` models `queryable` if - for each callable object `q` and a pack of subexpressions - `args`, if requires { q(env, args...) } is `true` then - q(env, args...) meets any semantic requirements imposed - by `q`. +2. Let `env` be an object of type `Env`. The type `Env` models + `queryable` if for each callable object `q` and a pack of + subexpressions `args`, if `requires { q(env, args...) }` is `true` then + `q(env, args...)` meets any semantic requirements imposed by `q`. ## Asynchronous operations [async.ops] ## {#spec-execution-async.ops} @@ -5361,28 +5356,33 @@ template<class Initializer> 2. An asynchronous operation is a distinct unit of program execution that: - - is explicitly created; + 1. ... is explicitly created. + + 2. ... can be explicitly started once at + most. + + 3. ... once started started, eventually completes exactly once with a (possibly empty) set + of result datums and in exactly one of three dispositions: success, failure, or + cancellation. - - can be explicitly started; an - asynchronous operation can be started once at most; + - A successful completion, also known as a value + completion, can have an arbitrary number of result datums. - - if started, eventually completes - with a (possibly empty) set of result datums, and in exactly one of - three modes: success, failure, or cancellation, known as the - operation's disposition; an asychronous - operation can only complete once; a successful completion, also known - as a value completion, can have an arbitrary - number of result datums; a failure completion, also known as an error completion, has a single result datum; a - cancellation completion, also known as a stopped - completion, has no result datum; an asynchronous operation's - async result is its disposition and its - (possibly empty) set of result datums. + - A failure completion, also known as an error + completion, has a single result datum. - - can complete on a different execution resource than that on which it - started; and + - A cancellation completion, also known as a stopped completion, has no result datum. - - can create and start other asychronous operations called async result is its + disposition and its (possibly empty) set of result datums. + + 4. ... can complete on a different execution resource than the execution + resource on which it started. + + 5. ... can create and start other asynchronous operations called child operations. A child operation is an asynchronous operation that is created by the parent operation and, if started, completes before the parent operation completes. A receiver's value completion handler with the value result datums; likewise for the error completion function and the stopped completion function. A completion function has an associated type known as its completion tag that names the unqualified type of the + export=true>completion tag that is the unqualified type of the completion function. A valid invocation of a completion function is called a completion operation. -7. The lifetime of an +7. The lifetime of an asynchronous operation, also known as the operation's async lifetime, begins when its start operation begins executing and ends when its completion operation begins executing. If the @@ -5484,8 +5484,8 @@ template<class Initializer> attributes that describes various characteristics of the sender and of the asynchronous operation(s) it produces. For each disposition, there is a query object for reading the associated completion - scheduler from a sender's attributes; *i.e.*, a value completion scheduler - query object for reading a sender's value completion scheduler, *etc*. If a + scheduler from a sender's attributes; i.e., a value completion scheduler + query object for reading a sender's value completion scheduler, etc. If a completion scheduler query is well-formed, the returned completion scheduler is unique for that disposition for any asynchronous operation the sender creates. A schedule sender is required to have a value completion scheduler @@ -5493,7 +5493,7 @@ template<class Initializer> sender. 13. A completion signature is a function type that - describes a completion operation. An asychronous operation has a finite set + describes a completion operation. An asynchronous operation has a finite set of possible completion signatures corresponding to the completion operations that the asynchronous operation potentially evaluates ([basic.def.odr]). For a completion function `set`, receiver @@ -5506,7 +5506,7 @@ template<class Initializer> a sender type and an environment type `Env` determine the set of completion signatures of an asynchronous operation that results from connecting the sender with a receiver that has an environment of type `Env`. The type of the receiver does not affect an asychronous + class="wg21note">The type of the receiver does not affect an asynchronous operation's completion signatures, only the type of the receiver's environment. @@ -5543,12 +5543,12 @@ namespace std { // [exec.queryable], queryable objects template<class T> - concept queryable = destructible<T>; + concept queryable = see above; // exposition only // [exec.queries], queries - struct forwarding_query_t; - struct get_allocator_t; - struct get_stop_token_t; + struct forwarding_query_t { see below }; + struct get_allocator_t { see below }; + struct get_stop_token_t { see below }; inline constexpr forwarding_query_t forwarding_query{}; inline constexpr get_allocator_t get_allocator{}; @@ -5565,13 +5565,17 @@ namespace std { namespace std::execution { // [exec.queries], queries - enum class forward_progress_guarantee; - struct get_domain_t; - struct get_scheduler_t; - struct get_delegatee_scheduler_t; - struct get_forward_progress_guarantee_t; + enum class forward_progress_guarantee { + concurrent, + parallel, + weakly_parallel + }; + struct get_domain_t { see below }; + struct get_scheduler_t { see below }; + struct get_delegatee_scheduler_t { see below }; + struct get_forward_progress_guarantee_t { see below }; template<class CPO> - struct get_completion_scheduler_t; + struct get_completion_scheduler_t { see below }; inline constexpr get_domain_t get_domain{}; inline constexpr get_scheduler_t get_scheduler{}; @@ -5581,8 +5585,8 @@ namespace std::execution { inline constexpr get_completion_scheduler_t<CPO> get_completion_scheduler{}; struct empty_env {}; - struct get_env_t; - inline constexpr get_env_t get_env {}; + struct get_env_t { see below }; + inline constexpr get_env_t get_env{}; template<class T> using env_of_t = decltype(get_env(declval<T>())); @@ -5605,9 +5609,9 @@ namespace std::execution { template<class Rcvr, class Completions> concept receiver_of = see below; - struct set_value_t; - struct set_error_t; - struct set_stopped_t; + struct set_value_t { see below }; + struct set_error_t { see below }; + struct set_stopped_t { see below }; inline constexpr set_value_t set_value{}; inline constexpr set_error_t set_error{}; @@ -5619,7 +5623,7 @@ namespace std::execution { template<class O> concept operation_state = see below; - struct start_t; + struct start_t { see below }; inline constexpr start_t start{}; // [exec.snd], senders @@ -5644,7 +5648,7 @@ namespace std::execution { concept single-sender = see below; // exposition only // [exec.getcomplsigs], completion signatures - struct get_completion_signatures_t; + struct get_completion_signatures_t { see below }; inline constexpr get_completion_signatures_t get_completion_signatures {}; template<class Sndr, class Env = empty_env> @@ -5674,18 +5678,18 @@ namespace std::execution { requires sender_in<Sndr, Env> inline constexpr bool sends_stopped = see below; - template <sender Sndr> - using tag_of_t = see below; + template<sender Sndr> + using tag_of_t = see below; // [exec.snd.transform], sender transformations - template<class Domain, sender Sndr, queryable... Env> + template<class Domain, sender Sndr, queryable... Env> requires (sizeof...(Env) <= 1) constexpr sender decltype(auto) transform_sender( Domain dom, Sndr&& sndr, const Env&... env) noexcept(see below); // [exec.snd.transform.env], environment transformations - template<class Domain, sender Sndr, queryable Env> - constexpr queryable decltype(auto) transform_env( + template<class Domain, sender Sndr, queryable Env> + constexpr queryable decltype(auto) transform_env( Domain dom, Sndr&& sndr, Env&& env) noexcept; // [exec.snd.apply], sender algorithm application @@ -5694,7 +5698,7 @@ namespace std::execution { Domain dom, Tag, Sndr&& sndr, Args&&... args) noexcept(see below); // [exec.connect], the connect sender algorithm - struct connect_t; + struct connect_t { see below }; inline constexpr connect_t connect{}; template<class Sndr, class Rcvr> @@ -5702,10 +5706,10 @@ namespace std::execution { decltype(connect(declval<Sndr>(), declval<Rcvr>())); // [exec.factories], sender factories - struct just_t; - struct just_error_t; - struct just_stopped_t; - struct schedule_t; + struct just_t { see below }; + struct just_error_t { see below }; + struct just_stopped_t { see below }; + struct schedule_t { see below }; inline constexpr just_t just{}; inline constexpr just_error_t just_error{}; @@ -5720,23 +5724,23 @@ namespace std::execution { template<class-type D> struct sender_adaptor_closure { }; - struct on_t; - struct transfer_t; - struct schedule_from_t; - struct then_t; - struct upon_error_t; - struct upon_stopped_t; - struct let_value_t; - struct let_error_t; - struct let_stopped_t; - struct bulk_t; - struct split_t; - struct ensure_started_t; - struct when_all_t; - struct when_all_with_variant_t; - struct into_variant_t; - struct stopped_as_optional_t; - struct stopped_as_error_t; + struct on_t { see below }; + struct transfer_t { see below }; + struct schedule_from_t { see below }; + struct then_t { see below }; + struct upon_error_t { see below }; + struct upon_stopped_t { see below }; + struct let_value_t { see below }; + struct let_error_t { see below }; + struct let_stopped_t { see below }; + struct bulk_t { see below }; + struct split_t { see below }; + struct ensure_started_t { see below }; + struct when_all_t { see below }; + struct when_all_with_variant_t { see below }; + struct into_variant_t { see below }; + struct stopped_as_optional_t { see below }; + struct stopped_as_error_t { see below }; inline constexpr on_t on{}; inline constexpr transfer_t transfer{}; @@ -5753,11 +5757,11 @@ namespace std::execution { inline constexpr when_all_t when_all{}; inline constexpr when_all_with_variant_t when_all_with_variant{}; inline constexpr into_variant_t into_variant{}; - inline constexpr stopped_as_optional_t stopped_as_optional; - inline constexpr stopped_as_error_t stopped_as_error; + inline constexpr stopped_as_optional_t stopped_as_optional{}; + inline constexpr stopped_as_error_t stopped_as_error{}; // [exec.consumers], sender consumers - struct start_detached_t; + struct start_detached_t { see below }; inline constexpr start_detached_t start_detached{}; // [exec.utils], sender and receiver utilities @@ -5801,11 +5805,11 @@ namespace std::execution { namespace std::this_thread { // [exec.queries], queries - struct execute_may_block_caller_t; + struct execute_may_block_caller_t { see below }; inline constexpr execute_may_block_caller_t execute_may_block_caller{}; - struct sync_wait_t; - struct sync_wait_with_variant_t; + struct sync_wait_t { see below }; + struct sync_wait_with_variant_t { see below }; inline constexpr sync_wait_t sync_wait{}; inline constexpr sync_wait_with_variant_t sync_wait_with_variant{}; @@ -5813,12 +5817,12 @@ namespace std::this_thread { namespace std::execution { // [exec.execute], one-way execution - struct execute_t; + struct execute_t { see below }; inline constexpr execute_t execute{}; // [exec.as.awaitable] - struct as_awaitable_t; - inline constexpr as_awaitable_t as_awaitable; + struct as_awaitable_t { see below }; + inline constexpr as_awaitable_t as_awaitable{}; // [exec.with.awaitable.senders] template<class-type Promise> @@ -5830,21 +5834,24 @@ namespace std::execution { defined as follows: 1. If `sizeof...(Ts)` is greater than zero, - variant-or-empty<Ts...> names the type + variant-or-empty<Ts...> denotes `variant` where `Us...` is the pack `decay_t...` with duplicate types removed. - 2. Otherwise, variant-or-empty<Ts...> names the + 2. Otherwise, variant-or-empty<Ts...> denotes the exposition-only class type:
         namespace std::execution {
-          struct empty-variant {
+          struct empty-variant { // exposition only
             empty-variant() = delete;
           };
         }
         
+ + + ## Queries [exec.queries] ## {#spec-execution.queries} ### `std::forwarding_query` [exec.fwd.env] ### {#spec-execution.forwarding_query} @@ -5914,7 +5921,7 @@ namespace std::execution { well-formed. * Mandates: The expression above is not potentially throwing, and - its type satisfies `queryable` ([exec.queryable]). + its type satisfies `queryable` ([exec.queryable]). 2. Otherwise, `empty_env{}`. @@ -6077,7 +6084,7 @@ namespace std::execution { template<class Sch> concept scheduler = enable-scheduler<remove_cvref_t<Sch>> && - queryable<Sch> && + queryable<Sch> && requires(Sch&& sch) { { schedule(std::forward<Sch>(sch)) } -> sender; { get_completion_scheduler<set_value_t>( @@ -6141,7 +6148,7 @@ namespace std::execution { concept receiver = enable-receiver<remove_cvref_t<Rcvr>> && requires(const remove_cvref_t<Rcvr>& rcvr) { - { get_env(rcvr) } -> queryable; + { get_env(rcvr) } -> queryable; } && move_constructible<remove_cvref_t<Rcvr>> && // rvalues are movable, and constructible_from<remove_cvref_t<Rcvr>, Rcvr>; // lvalues are copyable @@ -6217,7 +6224,7 @@ namespace std::execution { template<class O> concept operation_state = enable-opstate<remove_cvref_t<O>> && - queryable<O> && + queryable<O> && is_object_v<O> && requires (O& o) { { start(o) } noexcept; @@ -6467,7 +6474,7 @@ namespace std::execution { structured binding declaration [dcl.struct.bind].
14.
-        template <semiregular Tag, movable-value Data = see below, sender... Child>
+        template<semiregular Tag, movable-value Data = see below, sender... Child>
           constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
@@ -6623,10 +6630,10 @@ namespace std::execution { Childn-1 childn-1; // exposition only }; - template <class Sndr> + template<class Sndr> using data-type = decltype((declval<Sndr>().data)); // exposition only - template <class Sndr, size_t N = 0> + template<class Sndr, size_t N = 0> using child-type = decltype((declval<Sndr>().childN)); // exposition only }
@@ -6742,7 +6749,7 @@ namespace std::execution { concept sender = bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint requires (const remove_cvref_t<Sndr>& sndr) { - { get_env(sndr) } -> queryable; + { get_env(sndr) } -> queryable; } && move_constructible<remove_cvref_t<Sndr>> && // rvalues are movable, and constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable @@ -6750,7 +6757,7 @@ namespace std::execution { template<class Sndr, class Env = empty_env> concept sender_in = sender<Sndr> && - queryable<Env> && + queryable<Env> && requires (Sndr&& sndr, Env&& env) { { get_completion_signatures(std::forward<Sndr>(sndr), std::forward<Env>(env)) } -> valid-completion-signatures; @@ -6952,13 +6959,13 @@ namespace std::execution {
 namespace std::execution {
   struct default_domain {
-    template <sender Sndr, queryable... Env>
+    template<sender Sndr, queryable... Env>
         requires (sizeof...(Env) <= 1)
       static constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
         noexcept(see below);
 
-    template <sender Sndr, queryable Env>
-      static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+    template<sender Sndr, queryable Env>
+      static constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
 
     template<class Tag, sender Sndr, class... Args>
       static constexpr decltype(auto) apply_sender(Tag, Sndr&& sndr, Args&&... args)
@@ -6970,7 +6977,7 @@ namespace std::execution {
 #### Static members [exec.domain.default.statics] #### {#spec-execution.default_domain.statics}
 
 
-template <sender Sndr, queryable... Env>
+template<sender Sndr, queryable... Env>
     requires (sizeof...(Env) <= 1)
   constexpr sender decltype(auto) transform_sender(Sndr&& sndr, const Env&... env)
     noexcept(see below);
@@ -6985,8 +6992,8 @@ template <sender Sndr, queryable... Env>
 3. Remarks: The exception specification is equivalent to noexcept(e).
 
 
-template <sender Sndr, queryable Env>
-  constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
+template<sender Sndr, queryable Env>
+  constexpr queryable decltype(auto) transform_env(Sndr&& sndr, Env&& env) noexcept;
 
4. Let `e` be the expression @@ -7018,7 +7025,7 @@ template<class Tag, sender Sndr, class... Args>
 namespace std::execution {
-  template<class Domain, sender Sndr, queryable... Env>
+  template<class Domain, sender Sndr, queryable... Env>
       requires (sizeof...(Env) <= 1)
     constexpr sender decltype(auto) transform_sender(Domain dom, Sndr&& sndr, const Env&... env)
       noexcept(see below);
@@ -7044,8 +7051,8 @@ namespace std::execution {
 
 
 namespace std::execution {
-  template<class Domain, sender Sndr, queryable Env>
-    constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
+  template<class Domain, sender Sndr, queryable Env>
+    constexpr queryable decltype(auto) transform_env(Domain dom, Sndr&& sndr, Env&& env) noexcept;
 }
 
@@ -8311,7 +8318,7 @@ namespace std::execution { equivalent to the following:
-        template <class Sndr, class Rcvr>
+        template<class Sndr, class Rcvr>
         void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
         
@@ -8462,11 +8469,11 @@ namespace std::execution { enum class disposition { started, error, stopped }; - template <class Rcvr> + template<class Rcvr> struct make-state { const env_of_t<Rcvr>& env; - template <max-1-sender-in<env_of_t<Rcvr>>... Sndrs> + template<max-1-sender-in<env_of_t<Rcvr>>... Sndrs> auto operator()(auto, auto, Sndrs&&... sndrs) const { using values_tuple = see below; using errors_variant = see below; From 9c43d44ea6e60f14b8086936ac8a96ff9d7f57df Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 22 May 2024 15:35:46 -0700 Subject: [PATCH 59/89] feedback from the 2024-05-22 LWG telecon --- execution.bs | 219 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 154 insertions(+), 65 deletions(-) diff --git a/execution.bs b/execution.bs index 089a9af..ff6005b 100644 --- a/execution.bs +++ b/execution.bs @@ -1497,6 +1497,22 @@ concurrency, including: # Revision history # {#revisions} +## R10 ## {#r10} + +The changes since R8 are as follows: + +Fixes: + + +Enhancements: + + * The `get_delegatee_scheduler` query has been renamed to + `get_delegation_scheduler`. + + * An exposition-only `simple-allocator` concept is added to the + Library introduction ([library]), and the specification of the + `get_allocator` query is expressed in terms of it. + ## R9 ## {#r9} The changes since R8 are as follows: @@ -3185,8 +3201,8 @@ execution::sender auto read(auto tag); execution::sender auto get_scheduler() { return read(execution::get_scheduler); } -execution::sender auto get_delegatee_scheduler() { - return read(execution::get_delegatee_scheduler); +execution::sender auto get_delegation_scheduler() { + return read(execution::get_delegation_scheduler); } execution::sender auto get_allocator() { return read(execution::get_allocator); @@ -4020,6 +4036,72 @@ a new bullet as follows:
+ + + +
+
General [allocator.requirements.general]
+ +At the end of [allocator.requirements.general], add the +following new paragraph: + +98. [*Example 2*: The following is an allocator class template supporting the + minimal interface that meets the requirements of + [allocator.requirements.general]: + +
+    template<class T>
+    struct SimpleAllocator {
+      using value_type = T;
+      SimpleAllocator(ctor args);
+
+      template<class U> SimpleAllocator(const SimpleAllocator<U>& other);
+
+      T* allocate(std::size_t n);
+      void deallocate(T* p, std::size_t n);
+
+      template<class U> bool operator==(const SimpleAllocator<U>& rhs) const;
+    };
+    
+ + -- *end example*] + +
+99. The following exposition-only concept defines the minimal requirements on an + Allocator type. + +
+    template<class Alloc>
+    concept simple-allocator =
+      requires(Alloc alloc, size_t n, typename Alloc::value_type* p) {
+        { alloc.allocate(n) } -> same_as<typename Alloc::value_type*>;
+        { alloc.deallocate(p, n) };
+      } &&
+      copy_constructible<Alloc> &&
+      equality_comparable<Alloc>;
+    
+ + 1. A type `Alloc` models `simple-allocator` if it meets the requirements of + [allocator.requirements.general]. + +
+
+ // 33.3.3, class stop_token @@ -4600,7 +4600,7 @@ namespace std { 1. `stop-state` refers to the `stop_token`'s associated stop state. A `stop_token` object is disengaged when `stop-state` is empty. - +
@@ -4881,7 +4881,7 @@ bool request_stop() noexcept; associated `stop_callback` objects are synchronously called. If an invocation of a callback exits via an exception then `terminate` is invoked ([except.terminate]). - + A stop request includes notifying all condition variables of type `condition_variable_any` temporarily registered during an interruptible wait ([thread.condvarany.intwait]). @@ -4918,7 +4918,7 @@ friend void swap(stop_source& x, stop_source& y) noexcept; #### General [stopcallback.general] #### {#spec-stopcallback.general} -1. +1.
 namespace std {
@@ -5350,7 +5350,7 @@ template<class Initializer>
     1. For a subexpression expr, let
         MANDATE-NOTHROW(expr)
         be expression-equivalent to expr.
-        
+
         * Mandates: noexcept(expr) is
             true.
 
@@ -6330,29 +6330,27 @@ namespace std::execution {
     associated with the operation state `op`, the behavior of calling
     `start(op)` is undefined.
 
-
-
 ## Senders [exec.snd] ## {#spec-execution.senders}
 
 ### General [exec.snd.general] ### {#spec-execution.senders.general}
 
-1. For the purposes of this subclause, a sender is an object that satisfies the
-    `sender` concept ([async.ops]).
+1. For the purposes of this subclause, a sender is an object whose type
+    satisfies the `sender` concept ([async.ops]).
 
 2. Subclauses [exec.factories] and [exec.adapt] define customizable algorithms
     that return senders. Each algorithm has a default implementation. Let `sndr`
     be the result of an invocation of such an algorithm or an object equal to
-    such ([concepts.equality]), and let `Sndr` be `decltype((sndr))`. Let `rcvr`
-    be a receiver with associated environment `env` of type `Env` such that
-    `sender_in` is `true`. For the default implementation of the
+    the result ([concepts.equality]), and let `Sndr` be `decltype((sndr))`. Let `rcvr`
+    be a receiver of type `Rcvr` with associated environment `env` of type `Env` such that
+    `sender_to` is `true`. For the default implementation of the
     algorithm that produced `sndr`, connecting `sndr` to `rcvr` and starting the
     resulting operation state ([async.ops]) necessarily results in the potential
     evaluation ([basic.def.odr]) of a set of completion operations whose first
     argument is a subexpression equal to `rcvr`. Let `Sigs` be a pack of
     completion signatures corresponding to this set of completion operations.
     Then the type of the expression `get_completion_signatures(sndr, env)` is a
-    specialization of the class template `completion_signatures`,
-    ([exec.utils.cmplsigs]) the set of whose template arguments is `Sigs`. If a
+    specialization of the class template `completion_signatures`
+    ([exec.utils.cmplsigs]), the set of whose template arguments is `Sigs`. If a
     user-provided implementation of the algorithm that produced `sndr` is
     selected instead of the default, any completion signature that is in the set
     of types denoted by `completion_signatures_of_t` and that is not
@@ -6361,22 +6359,22 @@ namespace std::execution {
 
 3. This subclause makes use of the following exposition-only entities.
 
-    1. For a queryable object `env`, let FWD-ENV(env) be a
-        queryable object such that for a query object `q` and a pack of
-        subexpressions `as`, the expression
+    1. For a queryable object `env`, FWD-ENV(env) is an
+        expression whose type satisfies *`queryable`* such that for a query object
+        `q` and a pack of subexpressions `as`, the expression
         FWD-ENV(env).query(q, as...) is ill-formed if
-        `forwarding_query(q)` is `false`;
-        otherwise, it is expression-equivalent to `env.query(q, as...)`.
+        `forwarding_query(q)` is `false`; otherwise, it is expression-equivalent
+        to `env.query(q, as...)`.
 
-    2. For a query object `q` and a subexpression `v`, let
-        MAKE-ENV(q, v) be a queryable object `env` such that
-        the result of `env.query(q)` has a value equal to `v`
+    2. For a query object `q` and a subexpression `v`, MAKE-ENV(q,
+        v) is an expression `env` whose type satisfies *`queryable`* such
+        that the result of `env.query(q)` has a value equal to `v`
         ([concepts.equality]). Unless otherwise stated, the object to which
         `env.query(q)` refers remains valid while `env` remains valid.
 
     3. For two queryable objects `env1` and `env2`, a query object `q` and a
-        pack of subexpressions `as`, let JOIN-ENV(env1,
-        env2) be a queryable object `env3` such that
+        pack of subexpressions `as`, JOIN-ENV(env1, env2) is
+        an expression `env3` whose type satisfies *`queryable`* such that
         `env3.query(q, as...)` is expression-equivalent to:
 
           - `env1.query(q, as...)` if that expression is well-formed,
@@ -6386,27 +6384,27 @@ namespace std::execution {
 
           - otherwise, `env3.query(q, as...)` is ill-formed.
 
-    4. The expansions of `FWD-ENV`, `MAKE-ENV`, and
-        `JOIN-ENV` can be context-dependent; *i.e.*, they can expand to
-        expressions with different types and value categories in different
-        contexts for the same arguments.
+    4. The results of `FWD-ENV`, `MAKE-ENV`, and `JOIN-ENV`
+        can be context-dependent; i.e., they can evaluate to expressions with
+        different types and value categories in different contexts for the same
+        arguments.
 
-    5. For a scheduler `sch`, let SCHED-ATTRS(sch) be a
-        queryable object `o1` such that
+    5. For a scheduler `sch`, SCHED-ATTRS(sch) is an
+        expression `o1` whose type satisfied *`queryable`* such that
         o1.query(get_completion_scheduler<Tag>) is a
-        prvalue with the same type and value as `sch` where `Tag` is one
-        of `set_value_t` or `set_stopped_t`; and let
-        o1.query(get_domain) be expression-equivalent to
-        sch.query(get_domain). Let
-        SCHED-ENV(sch) be a queryable object `o2` such that
-        o1.query(get_scheduler) is a prvalue with the same
-        type and value as `sch`, and let o2.query(get_domain)
-        be expression-equivalent to sch.query(get_domain).
-
-    6. For two subexpressions `rcvr` and `expr`, let SET-VALUE(rcvr,
-        expr) be `(expr, set_value(rcvr))` if the type of `expr` is `void`;
-        otherwise, it is `set_value(rcvr, expr)`. Let
-        TRY-EVAL(rcvr, expr) be:
+        expression with the same type and value as `sch` where `Tag` is
+        one of `set_value_t` or `set_stopped_t`, and such that
+        o1.query(get_domain) is expression-equivalent to
+        sch.query(get_domain). SCHED-ENV(sch)
+        is an expression `o2` whose type satisfied *`queryable`* such that
+        o1.query(get_scheduler) is a prvalue with the same type and
+        value as `sch`, and such that o2.query(get_domain) is
+        expression-equivalent to sch.query(get_domain).
+
+    6. For two subexpressions `rcvr` and `expr`, SET-VALUE(rcvr,
+        expr) is expression-equivalent to `(expr, set_value(rcvr))` if
+        the type of `expr` is `void`; otherwise, `set_value(rcvr, expr)`.
+        TRY-EVAL(rcvr, expr) is equivalent to:
 
             
             try {
@@ -6416,28 +6414,29 @@ namespace std::execution {
             }
             
- if `expr` is potentially-throwing; otherwise, `expr`. Let - TRY-SET-VALUE(rcvr, expr) be - TRY-EVAL(rcvr, SET-VALUE(rcvr, expr)) - except that `rcvr` is evaluated only once. + if `expr` is potentially-throwing; otherwise, `expr`. + TRY-SET-VALUE(rcvr, expr) is + TRY-EVAL(rcvr, SET-VALUE(rcvr, expr)) except + that `rcvr` is evaluated only once. 7.
         template<class Default = default_domain, class Sndr>
           constexpr auto completion-domain(const Sndr& sndr) noexcept;
         
- 1. Let COMPL-DOMAIN(T) be the type of the + 1. COMPL-DOMAIN(T) is the type of the expression `get_domain(get_completion_scheduler(get_env(sndr)))`. - 2. *Effects:* If COMPL-DOMAIN(set_value_t), + 2. *Effects:* If all of the types + COMPL-DOMAIN(set_value_t), COMPL-DOMAIN(set_error_t), and - COMPL-DOMAIN(set_stopped_t) all share a common - type [meta.trans.other] (ignoring those types that are ill-formed), - then completion-domain<Default>(sndr) is a - default-constructed prvalue of that type. Otherwise, if all of those - types are ill-formed, + COMPL-DOMAIN(set_stopped_t) are ill-formed, completion-domain<Default>(sndr) is a - default-constructed prvalue of type `Default`. Otherwise, + default-constructed prvalue of type `Default`. Otherwise, if they + all share a common type ([meta.trans.other]) (ignoring those types + that are ill-formed), then + completion-domain<Default>(sndr) is a + default-constructed prvalue of that type. Otherwise, completion-domain<Default>(sndr) is ill-formed. @@ -6447,21 +6446,21 @@ namespace std::execution { Tag, const Env& env, Default&& value) noexcept(see below);
- 1. Let `e` be the expression `Tag()(env)` if that + 1. Let `e` be the expression `Tag()(env)` if that expression is well-formed; otherwise, it is `static_cast(std::forward(value))`. - 2. Returns: `e`. + 2. Returns: `e`. 3. Remarks: The expression in the `noexcept` clause is - noexcept(e). + `noexcept(e)`. 9.
         template<class Sndr>
           constexpr auto get-domain-early(const Sndr& sndr) noexcept;
         
- 1. Effects: Equivalent to return Domain(); + 1. Effects: Equivalent to: return Domain(); where `Domain` is the decayed type of the first of the following expressions that is well-formed: @@ -6484,14 +6483,23 @@ namespace std::execution {
                 [] {
-                  auto [ignore1, sch, ignore2] = sndr;
+                  auto [_, sch, _] = sndr;
                   return query-or-default(get_domain, sch, default_domain());
                 }();
                 
+ The `transfer` algorithm works in tandem + with `schedule_from` ([exec.schedule.from])) to give scheduler + authors a way to customize both how to transition onto + (`transfer`) and off of (`schedule_from`) a given execution + context. Thus, `transfer` must ignore the domain of the + predecessor and use the domain of the destination scheduler to + select a customization, a property that is unique to `transfer`. + That is why it is given special treatment here. + - Otherwise, return Domain(); where `Domain` is - the first of the following expressions that is well-formed and has class - type: + the first of the following expressions that is well-formed and + its type is not `void`: - `get_domain(get_env(sndr))` @@ -6503,11 +6511,6 @@ namespace std::execution { - `default_domain()`. - The `transfer` algorithm is unique in that it - ignores the execution domain of its predecessor, using only the - domain of its destination scheduler to select a - customization. - 11.
         template<callable Fun>
           requires is_nothrow_move_constructible_v<Fun>
@@ -6526,7 +6529,8 @@ namespace std::execution {
         
1. `emplace-from` is used to emplace - non-movable types into containers like `tuple`, `optional`, and `variant`. + non-movable types into `tuple`, `optional`, `variant`, and similar + types. 12.
         struct on-stop-request { // exposition only
@@ -6554,12 +6558,22 @@ namespace std::execution {
             `product-type` is usable as the initializer of a
             structured binding declaration [dcl.struct.bind].
 
+
+
     14. 
-        template<semiregular Tag, movable-value Data = see below, sender... Child>
+        template<class Tag, class Data = see below, class... Child>
           constexpr auto make-sender(Tag, Data&& data, Child&&... child);
         
- 1. *Returns:* A prvalue of type basic-sender<Tag, + 1. *Mandates:* The following expressions are `true`: + + - `semiregular` + + - movable-value<Data> + + - `(sender &&...)` + + 2. *Returns:* A prvalue of type basic-sender<Tag, decay_t<Data>, decay_t<Child>...> where the `tag` member has been default-initialized and the `data` and @@ -6570,22 +6584,13 @@ namespace std::execution {
               namespace std::execution {
-                template<class T, class... Us>
-                concept one-of = (same_as<T, Us> ||...); // exposition only
-
                 template<class Tag>
                 concept completion-tag = // exposition only
-                  one-of<Tag, set_value_t, set_error_t, set_stopped_t>;
+                  same_as<Tag, set_value_t> || same_as<Tag, set_error_t> || same_as<Tag, set_stopped_t>;
 
                 template<template<class...> class T, class... Args>
                 concept well-formed = requires { typename T<Args...>; }; // exposition only
 
-                template<const auto& Fun, class... Args>
-                concept cpo-callable = callable<decltype(Fun), Args...>; // exposition only
-
-                template<const auto& Fun, class... Args>
-                using cpo-result-t = call-result-t<decltype(Fun), Args...>; // exposition only
-
                 struct default-impls {  // exposition only
                   static constexpr auto get-attrs = see below;
                   static constexpr auto get-env = see below;
@@ -6598,86 +6603,89 @@ namespace std::execution {
                 struct impls-for : default-impls {}; // exposition only
 
                 template<class Sndr, class Rcvr> // exposition only
-                using state-type = decay_t<cpo-result-t<
-                  impls-for<tag_of_t<Sndr>>::get-state, Sndr, Rcvr&>>;
+                using state-type = decay_t<call-result-t<
+                  decltype(impls-for<tag_of_t<Sndr>>::get-state), Sndr, Rcvr&>>;
 
                 template<class Index, class Sndr, class Rcvr> // exposition only
-                using env-type = cpo-result-t<
-                  impls-for<tag_of_t<Sndr>>::get-env, Index,
+                using env-type = call-result-t<
+                  decltype(impls-for<tag_of_t<Sndr>>::get-env), Index,
                   state-type<Sndr, Rcvr>&, const Rcvr&>>;
 
-                template<class Sndr, class Rcvr, class Index> 
+                template<class Sndr>
+                using data-type = decltype((declval<Sndr>().data)); // exposition only
+
+                template<class Sndr, size_t N = 0>
+                using child-type = decltype((declval<Sndr>().childN)); // exposition only
+
+                template<class Sndr>
+                using indices-for = typename remove_reference_t<Sndr>::indices-for; // exposition only
+
+                template<class Sndr, class Rcvr>
+                struct basic-state { // exposition only
+                  basic-state(Sndr&& sndr, Rcvr&& rcvr) noexcept(see below)
+                    : rcvr(std::move(rcvr))
+                    , state(impls-for<tag_of_t<Sndr>>::get-state(std::forward<Sndr>(sndr), rcvr)) { }
+
+                  Rcvr rcvr; // exposition only
+                  state-type<Sndr, Rcvr> state; // exposition only
+                };
+
+                template<class Sndr, class Rcvr, class Index>
                   requires well-formed<env-type, Index, Sndr, Rcvr>
                 struct basic-receiver {  // exposition only
                   using receiver_concept = receiver_t;
 
-                  using tag-type = tag_of_t<Sndr>; // exposition only
-                  using state-type = state-type<Sndr, Rcvr>; // exposition only
-                  static constexpr const auto& complete = impls-for<tag-type>::complete; // exposition only
+                  using tag-t = tag_of_t<Sndr>; // exposition only
+                  using state-t = state-type<Sndr, Rcvr>; // exposition only
+                  static constexpr const auto& complete = impls-for<tag-t>::complete; // exposition only
 
                   template<class... Args>
-                    requires cpo-callable<complete, Index, state-type&, Rcvr&, set_value_t, Args...>
+                    requires callable<decltype(complete), Index, state-t&, Rcvr&, set_value_t, Args...>
                   void set_value(Args&&... args) && noexcept {
                     complete(Index(), op->state, op->rcvr, set_value_t(), std::forward<Args>(args)...);
                   }
 
                   template<class Error>
-                    requires cpo-callable<complete, Index, state-type&, Rcvr&, set_error_t, Error>
+                    requires callable<decltype(complete), Index, state-t&, Rcvr&, set_error_t, Error>
                   void set_error(Error&& err) && noexcept {
                     complete(Index(), op->state, op->rcvr, set_error_t(), std::forward<Error>(err));
                   }
 
                   void set_stopped() && noexcept
-                    requires cpo-callable<complete, Index, state-type&, Rcvr&, set_stopped_t> {
+                    requires callable<decltype(complete), Index, state-t&, Rcvr&, set_stopped_t> {
                     complete(Index(), op->state, op->rcvr, set_stopped_t());
                   }
 
                   auto get_env() const noexcept -> env-type<Index, Sndr, Rcvr> {
-                    const auto& rcvr = op->rcvr;
-                    return impls-for<tag-type>::get-env(Index(), op->state, rcvr);
+                    return impls-for<tag-t>::get-env(Index(), op->state, op->rcvr);
                   }
 
-                  basic-operation<Sndr, Rcvr>* op; // exposition only
+                  basic-state<Sndr, Rcvr>* op; // exposition only
                 };
 
-                constexpr auto connect-all =   // exposition only
-                  []<class Sndr, class Rcvr, size_t... Is>(
-                    basic-operation<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>)
-                      noexcept( TODO ) requires ( TODO ) {
-                      auto&& [ign1, ign2, ...child] = std::forward<Sndr>(sndr);
-                      return product-type{connect(
-                        std::forward_like<Sndr>(child),
-                        basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
-                    };
-
-                template<class Sndr>
-                using indices-for = make_index_sequence<tuple_size_v<Sndr>-2>; // exposition only
+                constexpr auto connect-all = see below; // exposition only
 
                 template<class Sndr, class Rcvr>
-                using inner-ops-tuple =   // exposition only
-                  cpo-result-t<connect-all, basic-operation<Sndr, Rcvr>*, Sndr,
-                    indices-for<Sndr>>;
+                using connect-all-result = call-result-t<  // exposition only
+                  decltype(connect-all), basic-state<Sndr, Rcvr>*, Sndr, indices-for<Sndr>>;
 
                 template<class Sndr, class Rcvr>
                   requires well-formed<state-type, Sndr, Rcvr> &&
-                    well-formed<inner-ops-tuple, Sndr, Rcvr>
-                struct basic-operation {  // exposition only
+                           well-formed<connect-all-result, Sndr, Rcvr>
+                struct basic-operation : basic-state<Sndr, Rcvr> {  // exposition only
                   using operation_state_concept = operation_state_t;
-                  using tag-type = tag_of_t<Sndr>; // exposition only
+                  using tag-t = tag_of_t<Sndr>; // exposition only
 
-                  Rcvr rcvr; // exposition only
-                  state-type<Sndr, Rcvr> state; // exposition only
-                  inner-ops-tuple<Sndr, Rcvr> inner-ops; // exposition only
+                  connect-all-result<Sndr, Rcvr> inner-ops; // exposition only
 
-                  basic-operation(Sndr&& sndr, Rcvr rcvr_init)  // exposition only
-                    : rcvr(std::move(rcvr_init))
-                    , state(impls-for<tag-type>::get-state(std::forward<Sndr>(sndr), rcvr))
+                  basic-operation(Sndr&& sndr, Rcvr&& rcvr) noexcept(see below)  // exposition only
+                    : basic-state<Sndr, Rcvr>(std::forward<Sndr>(sndr), std::move(rcvr))
                     , inner-ops(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
                   {}
 
                   void start() & noexcept {
                     auto& [...ops] = inner-ops;
-                    impls-for<tag-type>::start(state, rcvr, ops...);
+                    impls-for<tag-t>::start(this->state, this->rcvr, ops...);
                   }
                 };
 
@@ -6687,13 +6695,15 @@ namespace std::execution {
                 template<class Tag, class Data, class... Child>
                 struct basic-sender {  // exposition only
                   using sender_concept = sender_t;
+                  using indices-for = index_sequence_for<Child...>; // exposition only
 
                   decltype(auto) get_env() const noexcept {
                     return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
                   }
 
                   template<decays-to<basic-sender> Self, receiver Rcvr>
-                  auto connect(this Self&& self, Rcvr rcvr) -> basic-operation<Self, Rcvr> {
+                  auto connect(this Self&& self, Rcvr rcvr) noexcept(see below)
+                    -> basic-operation<Self, Rcvr> {
                     return {std::forward<Self>(self), std::move(rcvr)};
                   }
 
@@ -6710,58 +6720,93 @@ namespace std::execution {
                     ...
                   Childn-1 childn-1;   // exposition only
                 };
-
-                template<class Sndr>
-                using data-type = decltype((declval<Sndr>().data)); // exposition only
-
-                template<class Sndr, size_t N = 0>
-                using child-type = decltype((declval<Sndr>().childN)); // exposition only
               }
               
- 2. *Remarks:* The default template argument for the `Data` template parameter + 1. *Remarks:* The default template argument for the `Data` template parameter denotes an unspecified empty trivial class type. - 3. It is unspecified whether instances of `basic-sender` can be + 2. It is unspecified whether instances of `basic-sender` can be aggregate initialized. - 4. An expression of type + 3. An expression of type `basic-sender` is usable as the initializer of a structured binding declaration [dcl.struct.bind]. - 5. The member default-impls::get-attrs is + 4. The expression in the `noexcept` clause of the constructor of `basic-state` + is: + +
+            is_nothrow_move_constructible_v<Rcvr> &&
+            nothrow-callable<decltype(impls-for<tag_of_t<Sndr>>::get-state), Sndr, Rcvr&>
+            
+ + 5. The object `connect-all` is initialized with the following + lambda: + +
+              []<class Sndr, class Rcvr, size_t... Is>(
+                basic-state<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>) noexcept(noexcept(E))
+                  -> decltype(E) {
+                  return E;
+                }
+              
+ + where `E` is the following expression: + +
+              product-type{connect(
+                std::forward<Sndr>(sndr).childIs,
+                basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...}
+              
+ + 6. The expression in the `noexcept` clause of the constructor of `basic-operation` + is: + +
+            is_nothrow_constructible_v<basic-state<Self, Rcvr>, Self, Rcvr> &&
+            noexcept(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
+            
+ + 7. The expression in the `noexcept` clause of the `connect` member function of + `basic-sender` is: + +
+            is_nothrow_constructible_v<basic-operation<Self, Rcvr>, Self, Rcvr>
+            
+ + 8. The member default-impls::get-attrs is initialized with a callable object equivalent to the following lambda:
               [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
                 if constexpr (sizeof...(child) == 1)
-                  return FWD-ENV(get_env(child...));
+                  return (FWD-ENV(get_env(child)), ...);
                 else
                   return empty_env();
               }
               
- 6. The member default-impls::get-env is initialized + 9. The member default-impls::get-env is initialized with a callable object equivalent to the following lambda:
-              []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept
-                -> decltype(FWD-ENV(get_env(rcvr))) {
+              []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept -> decltype(auto) {
                 return FWD-ENV(get_env(rcvr));
               }
               
- 7. The member default-impls::get-state is initialized + 10. The member default-impls::get-state is initialized with a callable object equivalent to the following lambda:
               []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept -> decltype(auto) {
-                return get<1>(std::forward<Sndr>(sndr));
+                return (std::forward<Sndr>(sndr).data);
               }
               
- 8. The member default-impls::start is initialized + 11. The member default-impls::start is initialized with a callable object equivalent to the following lambda:
@@ -6770,7 +6815,7 @@ namespace std::execution {
               }
               
- 9. The member default-impls::complete is initialized + 12. The member default-impls::complete is initialized with a callable object equivalent to the following lambda:
@@ -6782,15 +6827,15 @@ namespace std::execution {
               }
               
- 10. For a subexpression `sndr` let `Sndr` be `decltype((sndr))`. Let - `rcvr` be a receiver that has an associated environment of type - `Env` such that `sender_in` is `true`. + 13. For a subexpression `sndr` let `Sndr` be `decltype((sndr))`. Let + `rcvr` be a receiver with an associated environment of type `Env` + such that `sender_in` is `true`. completion-signatures-for<Sndr, Env> denotes a specialization of `completion_signatures`, the set of whose template arguments correspond to the set of completion operations - that are potentially evaluated as a result of calling `start` on the - operation state that results from connecting `sndr` and `rcvr`. When - `sender_in` is `false`, the type denoted by + that are potentially evaluated as a result of starting ([async.ops]) + the operation state that results from connecting `sndr` and `rcvr`. + When `sender_in` is `false`, the type denoted by completion-signatures-for<Sndr, Env>, if any, is not a specialization of `completion_signatures`. @@ -6817,9 +6862,7 @@ namespace std::execution { template<class Sndr> concept is-sender = // exposition only - requires { - requires derived_from<typename Sndr::sender_concept, sender_t>; - }; + derived_from<typename Sndr::sender_concept, sender_t>; template<class Sndr> concept enable-sender = // exposition only From 315ab1a51b024ce17392d3a42e8c2cec47939834 Mon Sep 17 00:00:00 2001 From: Bryce Adelstein Lelbach aka wash Date: Tue, 11 Jun 2024 11:24:09 -0400 Subject: [PATCH 66/89] Remove erroneous scheduler parameter to a `when_all` call. --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index be386e9..0e240af 100644 --- a/execution.bs +++ b/execution.bs @@ -3485,7 +3485,7 @@ execution::scheduler auto sched = thread_pool.scheduler(); execution::sender auto sends_1 = ...; execution::sender auto sends_abc = ...; -execution::sender auto both = execution::when_all(sched, +execution::sender auto both = execution::when_all( sends_1, sends_abc ); From c2cec09ac0660ecab978b7e40e53eeb9ff6cba1b Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 13 Jun 2024 20:16:29 -0700 Subject: [PATCH 67/89] fix a copy/paste error in the `operation_state` concept --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 0e240af..98f25b0 100644 --- a/execution.bs +++ b/execution.bs @@ -6299,7 +6299,7 @@ namespace std::execution { namespace std::execution { template<class O> concept operation_state = - derived_from<typename Rcvr::operation_state_concept, operation_state_t> && + derived_from<typename O::operation_state_concept, operation_state_t> && is_object_v<O> && requires (O& o) { { start(o) } noexcept; From fee56a200a166e8b8ed5c9407fe43762f0de4cf4 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 13 Jun 2024 20:37:13 -0700 Subject: [PATCH 68/89] replace "is is" with "is" in the `let_value` specification --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 98f25b0..1040406 100644 --- a/execution.bs +++ b/execution.bs @@ -7971,7 +7971,7 @@ namespace std::execution {
4. impls-for<decayed-typeof<let-cpo>>::complete is - is initialized with a callable object equivalent to the following: + initialized with a callable object equivalent to the following:
             []<class Tag, class... Args>

From 41e9b3a5ef8c57ace02b1382e775df61de90fa92 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Tue, 25 Jun 2024 08:28:56 -0700
Subject: [PATCH 69/89] fix typos

---
 execution.bs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/execution.bs b/execution.bs
index 5667dd0..713f606 100644
--- a/execution.bs
+++ b/execution.bs
@@ -9018,8 +9018,8 @@ namespace std::execution {
         * The type sync-wait-result-type<Sndr> is well-formed.
 
         * same_as<decltype(e),
-            sync-wait-result-type<Sndr>> is `true`, where
-            `e` is `apply_sender` the expression above.
+            sync-wait-result-type<Sndr>> is `true`, where
+            `e` is the `apply_sender` expression above.
 
 5. Let `sync-wait-state` and
     `sync-wait-receiver` be the following exposition-only class

From 1ade302d9b041b317b0893821981c3aed2aa5230 Mon Sep 17 00:00:00 2001
From: Bryce Adelstein Lelbach aka wash 
Date: Tue, 25 Jun 2024 13:41:33 -0500
Subject: [PATCH 70/89] Remove erroneous formatting.

---
 execution.bs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/execution.bs b/execution.bs
index 713f606..e48aca8 100644
--- a/execution.bs
+++ b/execution.bs
@@ -1670,7 +1670,7 @@ object, obtainable from a receiver with a `get_env` accessor. In R6, the
 sender queries are given similar treatment, relocating to a "attributes"
 object obtainable from a sender with a `get_attrs` accessor. This was done
 to solve a number of design problems with the `split` and `ensure_started`
-algorithms; _e.g._, see
+algorithms; e.g., see
 [NVIDIA/stdexec#466](https://github.com/NVIDIA/stdexec/issues/466).
 
 Schedulers, however, remain directly queryable. As lightweight handles

From e7fb312acc459e8fbabbc91474f50a9bbede9152 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Tue, 25 Jun 2024 23:57:48 -0700
Subject: [PATCH 71/89] feedback from LWG wording review, 2024-06-25

---
 execution.bs | 576 ++++++++++++++++++++++++++++-----------------------
 1 file changed, 313 insertions(+), 263 deletions(-)

diff --git a/execution.bs b/execution.bs
index 713f606..74f723d 100644
--- a/execution.bs
+++ b/execution.bs
@@ -5965,7 +5965,7 @@ namespace std::execution {
     MANDATE-NOTHROW(as_const(env).query(get_allocator)).
 
       * Mandates: If the expression above is well-formed, its type
-          satisfies *`simple-allocator`* ([allocator.requirements.general]).
+          satisfies `simple-allocator` ([allocator.requirements.general]).
 
 3. `forwarding_query(get_allocator)` is a core constant expression and has value
     `true`.
@@ -6182,7 +6182,7 @@ namespace std::execution {
 
 2. Let `Sch` be the type of a scheduler and let `Env` be the type of an
     execution environment for which `sender_in, Env>` is
-    satisfied. Then sender-of-in<schedule_result_t<Sch>,
+    satisfied. Then sender-in-of<schedule_result_t<Sch>,
     Env> shall be modeled.
 
 3. None of a scheduler's copy constructor, destructor, equality comparison, or
@@ -6360,21 +6360,21 @@ namespace std::execution {
 3. This subclause makes use of the following exposition-only entities.
 
     1. For a queryable object `env`, FWD-ENV(env) is an
-        expression whose type satisfies *`queryable`* such that for a query object
+        expression whose type satisfies `queryable` such that for a query object
         `q` and a pack of subexpressions `as`, the expression
         FWD-ENV(env).query(q, as...) is ill-formed if
         `forwarding_query(q)` is `false`; otherwise, it is expression-equivalent
         to `env.query(q, as...)`.
 
     2. For a query object `q` and a subexpression `v`, MAKE-ENV(q,
-        v) is an expression `env` whose type satisfies *`queryable`* such
+        v) is an expression `env` whose type satisfies `queryable` such
         that the result of `env.query(q)` has a value equal to `v`
         ([concepts.equality]). Unless otherwise stated, the object to which
         `env.query(q)` refers remains valid while `env` remains valid.
 
     3. For two queryable objects `env1` and `env2`, a query object `q` and a
         pack of subexpressions `as`, JOIN-ENV(env1, env2) is
-        an expression `env3` whose type satisfies *`queryable`* such that
+        an expression `env3` whose type satisfies `queryable` such that
         `env3.query(q, as...)` is expression-equivalent to:
 
           - `env1.query(q, as...)` if that expression is well-formed,
@@ -6390,13 +6390,13 @@ namespace std::execution {
         arguments.
 
     5. For a scheduler `sch`, SCHED-ATTRS(sch) is an
-        expression `o1` whose type satisfied *`queryable`* such that
+        expression `o1` whose type satisfies `queryable` such that
         o1.query(get_completion_scheduler<Tag>) is a
         expression with the same type and value as `sch` where `Tag` is
         one of `set_value_t` or `set_stopped_t`, and such that
         o1.query(get_domain) is expression-equivalent to
         sch.query(get_domain). SCHED-ENV(sch)
-        is an expression `o2` whose type satisfied *`queryable`* such that
+        is an expression `o2` whose type satisfies `queryable` such that
         o1.query(get_scheduler) is a prvalue with the same type and
         value as `sch`, and such that o2.query(get_domain) is
         expression-equivalent to sch.query(get_domain).
@@ -6460,8 +6460,8 @@ namespace std::execution {
           constexpr auto get-domain-early(const Sndr& sndr) noexcept;
         
- 1. Effects: Equivalent to: return Domain(); - where `Domain` is the decayed type of the first of the + 1. Effects: Equivalent to: return Domain(); + where `Domain` is the decayed type of the first of the following expressions that is well-formed: - `get_domain(get_env(sndr))` @@ -6492,14 +6492,14 @@ namespace std::execution { with `schedule_from` ([exec.schedule.from])) to give scheduler authors a way to customize both how to transition onto (`transfer`) and off of (`schedule_from`) a given execution - context. Thus, `transfer` must ignore the domain of the - predecessor and use the domain of the destination scheduler to - select a customization, a property that is unique to `transfer`. - That is why it is given special treatment here. + context. Thus, `transfer` ignores the domain of the predecessor + and uses the domain of the destination scheduler to select a + customization, a property that is unique to `transfer`. That is + why it is given special treatment here. - - Otherwise, return Domain(); where `Domain` is + - Otherwise, return Domain(); where `Domain` is the first of the following expressions that is well-formed and - its type is not `void`: + whose type is not `void`: - `get_domain(get_env(sndr))` @@ -6540,17 +6540,19 @@ namespace std::execution { 13.
-        template<class... T>
+        template<class T0, class T1, ... class Tn>
         struct product-type {  // exposition only
-          using type0 = T0;      // exposition only
-          using type1 = T1;      // exposition only
-            ...
-          using typen-1 = Tn-1;   // exposition only
-
           T0 t0;      // exposition only
           T1 t1;      // exposition only
             ...
-          Tn-1 tn-1;   // exposition only
+          Tn tn;      // exposition only
+
+          template<size_t I, class Self>
+          constexpr decltype(auto) get(this Self&& self) noexcept; // exposition only
+
+          template<class Self, class Fn>
+          constexpr decltype(auto) apply(this Self&& self, Fn&& fn) // exposition only
+            noexcept(see below);
         };
         
@@ -6558,7 +6560,35 @@ namespace std::execution { `product-type` is usable as the initializer of a structured binding declaration [dcl.struct.bind]. - + 2.
+            template<size_t I, class Self>
+            constexpr decltype(auto) get(this Self&& self) noexcept;
+            
+ + 1. *Effects:* Equivalent to: + +
+                auto& [...ts] = self;
+                return std::forward_like<Self>(ts...\[I]);
+                
+ + 3.
+            template<class Self, class Fn>
+            constexpr decltype(auto) apply(this Self&& self, Fn&& fn) noexcept(see below);
+            
+ + 1. *Effects:* Equivalent to: + +
+                auto& [...ts] = self;
+                return std::forward<Fn>(fn)(std::forward_like<Self>(ts)...);
+                
+ + 2. *Requires:* The expression in the `return` statement above is + well-formed. + + 4. *Remarks:* The expression in the `noexcept` clause is `true` if the + `return` statement above is not potentially throwing; otherwise, `false`. 14.
         template<class Tag, class Data = see below, class... Child>
@@ -6574,11 +6604,8 @@ namespace std::execution {
             - `(sender &&...)`
 
         2. *Returns:* A prvalue of type basic-sender<Tag,
-            decay_t<Data>, decay_t<Child>...> where the
-            `tag` member has been default-initialized and the
-            `data` and
-            childn... members have been direct
-            initialized from their respective forwarded arguments, where
+            decay_t<Data>, decay_t<Child>...> that has been
+            direct-list-initialized with the forwarded arguments, where
             `basic-sender` is the following exposition-only
             class template except as noted below:
 
@@ -6589,7 +6616,7 @@ namespace std::execution {
                   same_as<Tag, set_value_t> || same_as<Tag, set_error_t> || same_as<Tag, set_stopped_t>;
 
                 template<template<class...> class T, class... Args>
-                concept well-formed = requires { typename T<Args...>; }; // exposition only
+                concept valid-specialization = requires { typename T<Args...>; }; // exposition only
 
                 struct default-impls {  // exposition only
                   static constexpr auto get-attrs = see below;
@@ -6609,16 +6636,13 @@ namespace std::execution {
                 template<class Index, class Sndr, class Rcvr> // exposition only
                 using env-type = call-result-t<
                   decltype(impls-for<tag_of_t<Sndr>>::get-env), Index,
-                  state-type<Sndr, Rcvr>&, const Rcvr&>>;
+                  state-type<Sndr, Rcvr>&, const Rcvr&>;
 
-                template<class Sndr>
-                using data-type = decltype((declval<Sndr>().data)); // exposition only
-
-                template<class Sndr, size_t N = 0>
-                using child-type = decltype((declval<Sndr>().childN)); // exposition only
+                template<class Sndr, size_t I = 0>
+                using child-type = decltype(declval<Sndr>().template get<I+2>()); // exposition only
 
                 template<class Sndr>
-                using indices-for = typename remove_reference_t<Sndr>::indices-for; // exposition only
+                using indices-for = remove_reference_t<Sndr>::indices-for; // exposition only
 
                 template<class Sndr, class Rcvr>
                 struct basic-state { // exposition only
@@ -6631,7 +6655,7 @@ namespace std::execution {
                 };
 
                 template<class Sndr, class Rcvr, class Index>
-                  requires well-formed<env-type, Index, Sndr, Rcvr>
+                  requires valid-specialization<env-type, Index, Sndr, Rcvr>
                 struct basic-receiver {  // exposition only
                   using receiver_concept = receiver_t;
 
@@ -6670,8 +6694,8 @@ namespace std::execution {
                   decltype(connect-all), basic-state<Sndr, Rcvr>*, Sndr, indices-for<Sndr>>;
 
                 template<class Sndr, class Rcvr>
-                  requires well-formed<state-type, Sndr, Rcvr> &&
-                           well-formed<connect-all-result, Sndr, Rcvr>
+                  requires valid-specialization<state-type, Sndr, Rcvr> &&
+                           valid-specialization<connect-all-result, Sndr, Rcvr>
                 struct basic-operation : basic-state<Sndr, Rcvr> {  // exposition only
                   using operation_state_concept = operation_state_t;
                   using tag-t = tag_of_t<Sndr>; // exposition only
@@ -6690,15 +6714,16 @@ namespace std::execution {
                 };
 
                 template<class Sndr, class Env>
-                using completion-signatures-for =  see below; // exposition only
+                using completion-signatures-for = see below; // exposition only
 
                 template<class Tag, class Data, class... Child>
-                struct basic-sender {  // exposition only
+                struct basic-sender : product-type<Tag, Data, Child...> {  // exposition only
                   using sender_concept = sender_t;
                   using indices-for = index_sequence_for<Child...>; // exposition only
 
                   decltype(auto) get_env() const noexcept {
-                    return impls-for<Tag>::get-attrs(data, child0, ... childn-1);
+                    auto& [_, data, ...child] = *this;
+                    return impls-for<Tag>::get-attrs(data, child...);
                   }
 
                   template<decays-to<basic-sender> Self, receiver Rcvr>
@@ -6712,26 +6737,19 @@ namespace std::execution {
                     -> completion-signatures-for<Self, Env> {
                     return {};
                   }
-
-                  Tag tag;            // exposition only
-                  Data data;          // exposition only
-                  Child0 child0;      // exposition only
-                  Child1 child1;      // exposition only
-                    ...
-                  Childn-1 childn-1;   // exposition only
                 };
               }
               
1. *Remarks:* The default template argument for the `Data` template parameter - denotes an unspecified empty trivial class type. + denotes an unspecified empty trivially copyable class type that models + `semiregular`. - 2. It is unspecified whether instances of `basic-sender` can be - aggregate initialized. + 2. It is unspecified whether a specialization of `basic-sender` is + an aggregate. - 3. An expression of type - `basic-sender` is usable as the initializer of a - structured binding declaration [dcl.struct.bind]. + 3. An expression of type `basic-sender` is usable as the initializer of a + structured binding declaration [dcl.struct.bind]. 4. The expression in the `noexcept` clause of the constructor of `basic-state` is: @@ -6741,30 +6759,30 @@ namespace std::execution { nothrow-callable<decltype(impls-for<tag_of_t<Sndr>>::get-state), Sndr, Rcvr&> - 5. The object `connect-all` is initialized with the following - lambda: + 5. The object `connect-all` is initialized with a callable object + equivalent to the following lambda:
               []<class Sndr, class Rcvr, size_t... Is>(
-                basic-state<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>) noexcept(noexcept(E))
-                  -> decltype(E) {
-                  return E;
+                basic-state<Sndr, Rcvr>* op, Sndr&& sndr, index_sequence<Is...>) noexcept(see below)
+                  -> decltype(auto) {
+                  auto& [_, data, ...child] = sndr;
+                  return product-type{connect(
+                    std::forward_like<Sndr>(child),
+                    basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...};
                 }
               
- where `E` is the following expression: + 1. *Requires:* The expression in the `return` statement is well-formed. -
-              product-type{connect(
-                std::forward<Sndr>(sndr).childIs,
-                basic-receiver<Sndr, Rcvr, integral_constant<size_t, Is>>{op})...}
-              
+ 2. *Remarks:* The expression in the `noexcept` clause is `true` if + the `return` statement is not potentially throwing; otherwise, `false`. 6. The expression in the `noexcept` clause of the constructor of `basic-operation` is:
-            is_nothrow_constructible_v<basic-state<Self, Rcvr>, Self, Rcvr> &&
+            is_nothrow_constructible_v<basic-state<Self, Rcvr>, Self, Rcvr> &&
             noexcept(connect-all(this, std::forward<Sndr>(sndr), indices-for<Sndr>()))
             
@@ -6772,7 +6790,7 @@ namespace std::execution { `basic-sender` is:
-            is_nothrow_constructible_v<basic-operation<Self, Rcvr>, Self, Rcvr>
+            is_nothrow_constructible_v<basic-operation<Self, Rcvr>, Self, Rcvr>
             
8. The member default-impls::get-attrs is @@ -6780,7 +6798,7 @@ namespace std::execution { lambda:
-              [](const auto& data, const auto&... child) noexcept -> decltype(auto) {
+              [](const auto&, const auto&... child) noexcept -> decltype(auto) {
                 if constexpr (sizeof...(child) == 1)
                   return (FWD-ENV(get_env(child)), ...);
                 else
@@ -6792,7 +6810,7 @@ namespace std::execution {
             with a callable object equivalent to the following lambda:
 
               
-              []<class Rcvr>(auto index, auto& state, const Rcvr& rcvr) noexcept -> decltype(auto) {
+              [](auto, auto&, const auto& rcvr) noexcept -> decltype(auto) {
                 return FWD-ENV(get_env(rcvr));
               }
               
@@ -6802,7 +6820,8 @@ namespace std::execution {
               []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept -> decltype(auto) {
-                return (std::forward<Sndr>(sndr).data);
+                auto& [_, data, ...child] = sndr;
+                return std::forward_like<Sndr>(data);
               }
               
@@ -6810,7 +6829,7 @@ namespace std::execution { with a callable object equivalent to the following lambda:
-              [](auto& state, auto& rcvr, auto&... ops) noexcept -> void {
+              [](auto&, auto&, auto&... ops) noexcept -> void {
                 (execution::start(ops), ...);
               }
               
@@ -6871,12 +6890,12 @@ namespace std::execution { template<class Sndr> concept sender = - bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint + bool(enable-sender<remove_cvref_t<Sndr>>) && // atomic constraint ([temp.constr.atomic]) requires (const remove_cvref_t<Sndr>& sndr) { { get_env(sndr) } -> queryable; } && - move_constructible<remove_cvref_t<Sndr>> && // rvalues are movable, and - constructible_from<remove_cvref_t<Sndr>, Sndr>; // lvalues are copyable + move_constructible<remove_cvref_t<Sndr>> && // senders are movable and + constructible_from<remove_cvref_t<Sndr>, Sndr>; // decay copyable template<class Sndr, class Env = empty_env> concept sender_in = @@ -6897,9 +6916,10 @@ namespace std::execution { }
-2. Given a subexpression `sndr`, let `Sndr` be `decltype((sndr))`, let `Env` be - the type of an environment, and let `rcvr` be a receiver with an associated - environment `Env`. A completion operation is a permissible completion for `Sndr` and `Env` if its completion signature appears in the argument list of the specialization of `completion_signatures` denoted by `completion_signatures_of_t`. @@ -6908,12 +6928,12 @@ namespace std::execution { starting the resulting operation state are permissible completions for `Sndr` and `Env`. -3. A type `Sigs` satisfies and models the exposition-only concept +3. A type models the exposition-only concept `valid-completion-signatures` if it denotes a specialization of the `completion_signatures` class template. 4. The exposition-only concepts `sender-of` and - `sender-of-in` define the requirements for a sender + `sender-in-of` define the requirements for a sender type that completes with a given unique set of value result types.
@@ -6922,14 +6942,14 @@ namespace std::execution {
         using value-signature = set_value_t(As...); // exposition only
 
       template<class Sndr, class Env, class... Values>
-        concept sender-of-in =
+        concept sender-in-of =
           sender_in<Sndr, Env> &&
           MATCHING-SIG( // see [exec.general]
             set_value_t(Values...),
             value_types_of_t<Sndr, Env, value-signature, type_identity_t>);
 
       template<class Sndr, class... Values>
-        concept sender-of = sender-of-in<Sndr, empty_env, Values...>;
+        concept sender-of = sender-in-of<Sndr, empty_env, Values...>;
     }
     
@@ -6971,20 +6991,18 @@ namespace std::execution { - Only expose an overload of a member `connect` that accepts an lvalue sender if they model `copy_constructible`. - - Model `copy_constructible` if they satisfy `copy_constructible`. - ### Awaitable helpers [exec.awaitables] ### {#spec.exec-awaitables} -1. The sender concepts recognize awaitables as senders. For this clause - ([exec]), an awaitable is an expression that would be +1. The sender concepts recognize awaitables as senders. For [exec], an + awaitable is an expression that would be well-formed as the operand of a `co_await` expression within a given context. 2. For a subexpression `c`, let GET-AWAITER(c, p) be expression-equivalent to the series of transformations and conversions applied to `c` as the operand of an *await-expression* in a coroutine, - resulting in lvalue `e` as described by [expr.await]/3.2-4, where `p` - is an lvalue referring to the coroutine's promise type, `Promise`. `e` as described by [expr.await], where `p` + is an lvalue referring to the coroutine's promise, which has type `Promise`. This includes the invocation of the promise type's `await_transform` member if any, the invocation of the `operator co_await` picked by overload resolution if any, and any necessary implicit @@ -7000,7 +7018,7 @@ namespace std::execution {
     namespace std {
       template<class T>
-      concept await-suspend-result = see below;
+      concept await-suspend-result = see below; // exposition only
 
       template<class A, class Promise>
       concept is-awaiter = // exposition only
@@ -7047,9 +7065,8 @@ namespace std::execution {
             }
 
           template<has-as-awaitable<Derived> T>
-            auto await_transform(T&& value)
-              noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>())))
-              -> decltype(std::forward<T>(value).as_awaitable(declval<Derived&>())) {
+            decltype(auto) await_transform(T&& value)
+              noexcept(noexcept(std::forward<T>(value).as_awaitable(declval<Derived&>()))) {
               return std::forward<T>(value).as_awaitable(static_cast<Derived&>(*this));
             }
         };
@@ -7217,12 +7234,14 @@ namespace std::execution {
 1. `get_completion_signatures` is a customization point object. Let `sndr` be an
     expression such that `decltype((sndr))` is `Sndr`, and let `env` be an
     expression such that `decltype((env))` is `Env`. Then
-    `get_completion_signatures(sndr, env)` is expression-equivalent to:
+    `get_completion_signatures(sndr, env)` is expression-equivalent to
+    (void(sndr), void(env), CS()) except that `void(sndr)`
+    and `void(env)` are indeterminately sequenced, where `CS` is:
 
-    1. `decltype(sndr.get_completion_signatures(env)){}` if that
-        expression is well-formed,
+    1. `decltype(sndr.get_completion_signatures(env))` if that
+        type is well-formed,
 
-    2. Otherwise, `remove_cvref_t::completion_signatures{}` if that expression is well-formed,
+    2. Otherwise, `remove_cvref_t::completion_signatures` if that type is well-formed,
 
     3. Otherwise, if is-awaitable<Sndr, env-promise<Env>>
         is `true`, then:
@@ -7232,13 +7251,14 @@ namespace std::execution {
               SET-VALUE-SIG(await-result-type<Sndr,
                             env-promise<Env>>), // see [exec.snd.concepts]
               set_error_t(exception_ptr),
-              set_stopped_t()>{}
+              set_stopped_t()>
             
- 4. Otherwise, `get_completion_signatures(sndr, env)` is ill-formed. + 4. Otherwise, `CS` is ill-formed. -2. Let `rcvr` be an rvalue receiver of type `Rcvr`, and let `Sndr` be the type of a - sender such that `sender_in>` is `true`. Let `Sigs...` be the +2. Let `rcvr` be an rvalue whose type `Rcvr` models `receiver`, and let `Sndr` + be the type of a sender such that `sender_in>` is + `true`. Let `Sigs...` be the template arguments of the `completion_signatures` specialization named by `completion_signatures_of_t>`. Let `CSO` be a completion function. If sender `Sndr` or its operation state cause the @@ -7254,16 +7274,15 @@ namespace std::execution { 2. The name `connect` denotes a customization point object. For subexpressions `sndr` and `rcvr`, let `Sndr` be `decltype((sndr))` and `Rcvr` be - `decltype((rcvr))`, and let `DS` and `DR` be the decayed types of `Sndr` and - `Rcvr`, respectively. + `decltype((rcvr))`, and let `DS` and `DR` be `decay_t` and + `decay_t`, respectively. -3. Let `connect-awaitable-promise` be the following class: +3. Let `connect-awaitable-promise` be the following exposition-only class:
     namespace std::execution {
       struct connect-awaitable-promise
         : with-await-transform<connect-awaitable-promise> {
-        DR& rcvr; // exposition only
 
         connect-awaitable-promise(DS&, DR& rcvr) noexcept : rcvr(rcvr) {}
 
@@ -7273,7 +7292,7 @@ namespace std::execution {
         [[noreturn]] void return_void() noexcept { terminate(); }
 
         coroutine_handle<> unhandled_stopped() noexcept {
-          set_stopped((DR&&) rcvr);
+          set_stopped(std::move(rcvr));
           return noop_coroutine();
         }
 
@@ -7282,21 +7301,23 @@ namespace std::execution {
             coroutine_handle<connect-awaitable-promise>::from_promise(*this)};
         }
 
-        env_of_t<const DR&> get_env() const noexcept {
+        env_of_t<DR> get_env() const noexcept {
           return execution::get_env(rcvr);
         }
+
+      private:
+        DR& rcvr; // exposition only
       };
     }
     
-4. Let `operation-state-task` be the following class: +4. Let `operation-state-task` be the following exposition-only class:
     namespace std::execution {
       struct operation-state-task {
         using operation_state_concept = operation_state_t;
         using promise_type = connect-awaitable-promise;
-        coroutine_handle<> coro; // exposition only
 
         explicit operation-state-task(coroutine_handle<> h) noexcept : coro(h) {}
         operation-state-task(operation-state-task&& o) noexcept
@@ -7306,6 +7327,9 @@ namespace std::execution {
         void start() & noexcept {
           coro.resume();
         }
+
+      private:
+        coroutine_handle<> coro; // exposition only
       };
     }
     
@@ -7337,7 +7361,7 @@ namespace std::execution { [[noreturn]] void await_resume() noexcept { unreachable(); } }; return awaiter{fn}; - }; + } operation-state-task connect-awaitable(DS sndr, DR rcvr) requires receiver_of<DR, Sigs> { exception_ptr ep; @@ -7356,8 +7380,7 @@ namespace std::execution { } -6. If `Sndr` does not satisfy `sender` or if `Rcvr` does not satisfy `receiver`, - `connect(sndr, rcvr)` is ill-formed. Otherwise, the expression `connect(sndr, rcvr)` is +6. The expression `connect(sndr, rcvr)` is expression-equivalent to: 1. `sndr.connect(rcvr)` if that expression is well-formed. @@ -7365,27 +7388,27 @@ namespace std::execution { * Mandates: The type of the expression above satisfies `operation_state`. - 2. Otherwise, connect-awaitable(sndr, rcvr) if that expression is - well-formed. + 2. Otherwise, connect-awaitable(sndr, rcvr). + + 3. *Mandates:* `sender && receiver` is `true`. - 3. Otherwise, `connect(sndr, rcvr)` is ill-formed. ### Sender factories [exec.factories] ### {#spec-execution.senders.factories} #### `execution::schedule` [exec.schedule] #### {#spec-execution.senders.schedule} -1. `schedule` obtains a schedule-sender ([async.ops]) from a scheduler. +1. `schedule` obtains a schedule sender ([async.ops]) from a scheduler. 2. The name `schedule` denotes a customization point object. For a - subexpression `sch`, the expression `schedule(sch)` is expression-equivalent to: + subexpression `sch`, the expression `schedule(sch)` is expression-equivalent to + `sch.schedule()`. + - 1. `sch.schedule()` if that expression is valid. If `sch.schedule()` does - not return a sender whose `set_value` completion scheduler is equal - to `sch`, the behavior of calling `schedule(sch)` is undefined. + 1. If the expression get_completion_scheduler<set_value_t>( + get_env(sch.schedule())) == sch is ill-formed or evaluates + to `false`, the behavior of calling `schedule(sch)` is undefined. - * Mandates: The type of `sch.schedule()` satisfies `sender`. - - 2. Otherwise, `schedule(sch)` is ill-formed. + 2. Mandates: The type of `sch.schedule()` satisfies `sender`. #### `execution::just`, `execution::just_error`, `execution::just_stopped` [exec.just] #### {#spec-execution.senders.just} @@ -7409,7 +7432,7 @@ namespace std::execution { is `false`; Otherwise, it is expression-equivalent to make-sender(just-cpo, - product-type{vs...}). + product-type{ts...}). 3. For `just`, `just_error`, and `just_stopped`, let `set-cpo` be `set_value`, `set_error`, and `set_stopped` respectively. The @@ -7459,33 +7482,34 @@ namespace std::execution { #### General [exec.adapt.general] #### {#spec-execution.senders.adapt.general} -1. Subclause [exec.adapt] specifies a set of sender adaptors. +1. [exec.adapt] specifies a set of sender adaptors. -2. The bitwise OR operator is overloaded for the purpose of creating sender +2. The bitwise inclusive OR operator is overloaded for the purpose of creating sender chains. The adaptors also support function call syntax with equivalent semantics. -3. Unless otherwise specified, a sender adaptor is prohibited from causing - observable effects, apart from moving and copying its arguments, before the - returned sender is connected with a receiver using `connect`, and `start` is - called on the resulting operation state. This requirement applies to any - function that is selected by the implementation of the sender adaptor. - -4. Unless otherwise specified, a parent sender ([async.ops]) with a single child - sender `sndr` has an associated attribute object equal to - FWD-ENV(get_env(sndr)) ([exec.fwd.env]). Unless - otherwise specified, a parent sender with more than one child senders has an - associated attributes object equal to empty_env{}. These - requirements apply to any function that is selected by the implementation of - the sender adaptor. - -5. Unless otherwise specified, when a parent sender is connected to a receiver - `rcvr`, any receiver used to connect a child sender has an associated - environment equal to FWD-ENV(get_env(rcvr)). This - requirement applies to any sender returned from a function that is selected - by the implementation of such sender adaptor. - -6. If a sender returned from a sender adaptor specified in this subclause is +3. Unless otherwise specified: + + 1. A sender adaptor is prohibited from causing observable effects, apart + from moving and copying its arguments, before the returned sender is + connected with a receiver using `connect`, and `start` is called on the + resulting operation state. + + 2. A parent sender ([async.ops]) with a single child + sender `sndr` has an associated attribute object equal to + FWD-ENV(get_env(sndr)) ([exec.fwd.env]). + + 3. A parent sender with more than one child sender has an + associated attributes object equal to empty_env{}. + + 4. When a parent sender is connected to a receiver `rcvr`, any receiver used + to connect a child sender has an associated environment equal to + FWD-ENV(get_env(rcvr)). + + These requirement apply to any function that is selected by the implementation + of the sender adaptor. + +4. If a sender returned from a sender adaptor specified in [exec.adapt] is specified to include `set_error_t(Err)` among its set of completion signatures where `decay_t` denotes the type `exception_ptr`, but the implementation does not potentially evaluate an error completion operation with an @@ -7495,7 +7519,7 @@ namespace std::execution { #### Sender adaptor closure objects [exec.adapt.objects] #### {#spec-execution.senders.adaptor.objects} 1. A pipeable sender adaptor closure object is a function object that - accepts one or more `sender` arguments and returns a `sender`. For a sender + accepts one or more `sender` arguments and returns a `sender`. For a pipeable sender adaptor closure object `c` and an expression `sndr` such that `decltype((sndr))` models `sender`, the following expressions are equivalent and yield a `sender`: @@ -7512,22 +7536,22 @@ namespace std::execution { `e` is a perfect forwarding call wrapper ([func.require]) with the following properties: - - Its target object is an object `d2` of type `decay_t` + - Its target object is an object `d2` of type `decltype(auto(d))` direct-non-list-initialized with `d`. - It has one bound argument entity, an object `c2` of type - `decay_t` direct-non-list-initialized with `C`. + `decltype(auto(c))` direct-non-list-initialized with `c`. - Its call pattern is `d2(c2(arg))`, where `arg` is the argument used in a function call expression of `e`. The expression `c | d` is well-formed if and only if the initializations of - the state entities of `e` are all well-formed. + the state entities ([func.def]) of `e` are all well-formed. 2. An object `t` of type `T` is a pipeable sender adaptor closure object if `T` models `derived_from>`, `T` has no other base classes of type `sender_adaptor_closure` for any other type `U`, and `T` - does not model `sender`. + does not satisfy `sender`. 3. The template parameter `D` for `sender_adaptor_closure` can be an incomplete type. Before any expression of type cv D appears as an @@ -7546,11 +7570,10 @@ namespace std::execution { 6. If a pipeable sender adaptor object `adaptor` accepts more than one argument, then let `sndr` be an expression such that `decltype((sndr))` models `sender`, let `args...` be arguments such that `adaptor(sndr, args...)` is a - well-formed expression as specified in the rest of this subclause - ([exec.adapt.objects]), and let `BoundArgs` be a pack that denotes - `decay_t...`. The expression `adaptor(args...)` produces a - pipeable sender adaptor closure object `f` that is a perfect forwarding call - wrapper with the following properties: + well-formed expression as specified below, and let `BoundArgs` be a pack + that denotes `decltype(auto(args))...`. The expression `adaptor(args...)` + produces a pipeable sender adaptor closure object `f` that is a perfect + forwarding call wrapper with the following properties: - Its target object is a copy of `adaptor`. @@ -7570,7 +7593,7 @@ namespace std::execution { 1. `on` adapts an input sender into a sender that will start on an execution agent belonging to a particular scheduler's associated execution resource. -2. The name `on` denotes a customization point object. For some subexpressions +2. The name `on` denotes a customization point object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, `on(sch, sndr)` is ill-formed. @@ -7579,9 +7602,11 @@ namespace std::execution {
         transform_sender(
           query-or-default(get_domain, sch, default_domain()),
-          make-sender(on, sch, sndr));
+          make-sender(on, sch, sndr))
         
+ except that `sch` is evaluated only once. + 4. Let `out_sndr` and `env` be subexpressions such that `OutSndr` is `decltype((out_sndr))`. If sender-for<OutSndr, on_t> is `false`, then the expressions `on.transform_env(out_sndr, env)` and `on.transform_sender(out_sndr, env)` are ill-formed; @@ -7590,17 +7615,18 @@ namespace std::execution { - `on.transform_env(out_sndr, env)` is equivalent to:
-            auto&& [ign1, sch, ign2] = out_sndr;
+            auto&& [_, sch, _] = out_sndr;
             return JOIN-ENV(SCHED-ENV(sch), FWD-ENV(env));
             
- `on.transform_sender(out_sndr, env)` is equivalent to:
-            auto&& [ign, sch, sndr] = out_sndr;
+            auto&& [_, sch, sndr] = out_sndr;
             return let_value(
               schedule(sch),
-              [sndr = std::forward_like<OutSndr>(sndr)]() mutable {
+              [sndr = std::forward_like<OutSndr>(sndr)]() mutable
+                noexcept(is_nothrow_move_constructible_v) {
                 return std::move(sndr);
               });
             
@@ -7611,16 +7637,14 @@ namespace std::execution { type `Env` such that `sender_in` is `true`. Let `op` be an lvalue referring to the operation state that results from connecting `out_sndr` with `out_rcvr`. Calling `start(op)` shall start `sndr` on an execution agent of the - associated execution resource of `sch`, or failing that, shall execute an - error completion on `out_rcvr`. + associated execution resource of `sch`. If scheduling onto `sch` fails, an error + completion on `out_rcvr` shall be executed on an unspecified execution agent. #### `execution::transfer` [exec.transfer] #### {#spec-execution.senders.adapt.transfer} -1. `transfer` adapts a sender into one with a different associated `set_value` - completion scheduler. It results in a transition - between different execution resources when executed. +1. `transfer` adapts a sender into one that completes on the specified scheduler. -2. The name `transfer` denotes a customization point object. For some +2. The name `transfer` denotes a customization point object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, `transfer(sndr, sch)` is ill-formed. @@ -7630,9 +7654,11 @@ namespace std::execution {
         transform_sender(
           get-domain-early(sndr),
-          make-sender(transfer, sch, sndr));
+          make-sender(transfer, sch, sndr))
         
+ except that `sndr` is evaluated only once. + 4. The exposition-only class template `impls-for` is specialized for `transfer_t` as follows: @@ -7654,13 +7680,13 @@ namespace std::execution { is equal to:
-        auto [tag, data, child] = sndr;
+        auto [_, data, child] = sndr;
         return schedule_from(std::move(data), std::move(child));
         
This causes the `transfer(sndr, sch)` sender to become - `schedule_from(sch, sndr)` when it is connected with a receiver with an - execution domain that does not customize `transfer`. + `schedule_from(sch, sndr)` when it is connected with a receiver whose + execution domain does not customize `transfer`.
6. Let `out_sndr` be a subexpression denoting a sender returned from `transfer(sndr, sch)` or one equal to such, and let `OutSndr` be the type @@ -7670,8 +7696,8 @@ namespace std::execution { results from connecting `out_sndr` with `out_rcvr`. Calling `start(op)` shall start `sndr` on the current execution agent and execute completion operations on `out_rcvr` on an execution agent of the execution resource - associated with `sch`. If scheduling onto `sch` fails, execute an error - completion on `out_rcvr` on an unspecified execution agent. + associated with `sch`. If scheduling onto `sch` fails, an error completion + on `out_rcvr` shall be executed on an unspecified execution agent. #### `execution::schedule_from` [exec.schedule.from] #### {#spec-execution.senders.adaptors.schedule_from} @@ -7683,7 +7709,7 @@ namespace std::execution { 2. The name `schedule_from` denotes a customization point object. For some subexpressions `sch` and `sndr`, let `Sch` be `decltype((sch))` and `Sndr` be `decltype((sndr))`. If `Sch` does not satisfy `scheduler`, or `Sndr` does not - satisfy `sender`, `schedule_from` is ill-formed. + satisfy `sender`, `schedule_from(sch, sndr)` is ill-formed. 3. Otherwise, the expression `schedule_from(sch, sndr)` is expression-equivalent to: @@ -7691,9 +7717,11 @@ namespace std::execution {
         transform_sender(
           query-or-default(get_domain, sch, default_domain()),
-          make-sender(schedule_from, sch, sndr));
+          make-sender(schedule_from, sch, sndr))
         
+ except that `sch` is evaluated only once. + 4. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `schedule_from_t` as follows: @@ -7722,30 +7750,32 @@ namespace std::execution { with a callable object equivalent to the following lambda:
-          []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
+          []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept(see below)
               requires sender_in<child-type<Sndr>, env_of_t<Rcvr>> {
-            return apply(
-              [&]<class Sch, class Child>(auto, Sch sch, Child&& child) {
-                using variant-type = see below;
-                using receiver-type = see below;
-                using operation-type = connect_result_t<schedule_result_t<Sch>, receiver-type>;
-
-                struct state-type {
-                  Rcvr& rcvr;
-                  variant-type async-result;
-                  operation-type op-state;
-
-                  explicit state-type(Sch sch, Rcvr& rcvr)
-                    : rcvr(rcvr), op-state(connect(schedule(sch), receiver-type{{}, this})) {}
-                };
 
-                return state-type{sch, rcvr};
-              },
-              std::forward<Sndr>(sndr));
+            auto& [_, sch, child] = sndr;
+
+            using sched-t = decltype(auto(sch));
+            using variant-type = see below;
+            using receiver-type = see below;
+            using operation-type = connect_result_t<schedule_result_t<sched-t>, receiver-type>;
+            constexpr bool nothrow = noexcept(connect(schedule(sch), receiver-type{nullptr}));
+
+            struct state-type {
+              Rcvr& rcvr;
+              variant-type async-result;
+              operation-type op-state;
+
+              explicit state-type(sched-t sch, Rcvr& rcvr) noexcept(nothrow)
+                : rcvr(rcvr), op-state(connect(schedule(sch), receiver-type{this})) {}
+            };
+
+            return state-type{sch, rcvr};
           }
           
- 1. The local class `state-type` is a structural type. + 1. Objects of the local class `state-type` can be used to + initialize a structured binding. 2. Let `Sigs` be a pack of the arguments to the `completion_signatures` specialization named by @@ -7766,9 +7796,6 @@ namespace std::execution { using receiver_concept = receiver_t; state-type* state; // exposition only - Rcvr&& base() && noexcept { return std::move(state->rcvr); } - const Rcvr& base() const & noexcept { return state->rcvr; } - void set_value() && noexcept { visit( [this]<class Tuple>(Tuple& result) noexcept -> void { @@ -7796,6 +7823,10 @@ namespace std::execution { } + 4. The expression in the `noexcept` clause of the lambda is `true` if + the construction of the returned `state-type` object is not + potentially throwing; otherwise, `false`. + 3. The member impls-for<schedule_from_t>::complete is initialized with a callable object equivalent to the following lambda: @@ -7817,18 +7848,16 @@ namespace std::execution { }; -5. Let the subexpression `out_sndr` denote the result of the invocation - `schedule_from(sch, sndr)` or an object copied or moved from such, and let - the subexpression `rcvr` denote a receiver such that the expression - `connect(out_sndr, rcvr)` is well-formed. The expression - `connect(out_sndr, rcvr)` has undefined behavior unless it creates an - asynchronous operation ([async.ops]) that, when started: - - - eventually completes on an execution agent belonging to the associated - execution resource of `sch`, and - - - completes with the same async result as `sndr`. - +5. Let `out_sndr` be a subexpression denoting a sender returned from + `schedule_from(sch, sndr)` or one equal to such, and let `OutSndr` be the type + `decltype((out_sndr))`. Let `out_rcvr` be a subexpression denoting a + receiver that has an environment of type `Env` such that `sender_in` is `true`. Let `op` be an lvalue referring to the operation state that + results from connecting `out_sndr` with `out_rcvr`. Calling `start(op)` + shall start `sndr` on the current execution agent and execute completion + operations on `out_rcvr` on an execution agent of the execution resource + associated with `sch`. If scheduling onto `sch` fails, an error completion + on `out_rcvr` shall be executed on an unspecified execution agent. #### `execution::then`, `execution::upon_error`, `execution::upon_stopped` [exec.then] #### {#spec-execution.senders.adaptor.then} @@ -7839,9 +7868,9 @@ namespace std::execution { 2. The names `then`, `upon_error`, and `upon_stopped` denote customization point objects. Let the expression `then-cpo` be one of `then`, - `upon_error`, or `upon_stopped`. For subexpressions `sndr` and `f`, let `Sndr` be - `decltype((sndr))` and let `F` be the decayed type of `f`. If `Sndr` does not - satisfy `sender`, or `F` does not satisfy `movable-value`, + `upon_error`, or `upon_stopped`. For subexpressions `sndr` and `f`, if + `decltype(sndr)` does not satisfy `sender`, or `decltype(f)` does not + satisfy `movable-value`, then-cpo(sndr, f) is ill-formed. 3. Otherwise, the expression then-cpo(sndr, f) is @@ -7850,8 +7879,10 @@ namespace std::execution {
         transform_sender(
           get-domain-early(sndr),
-          make-sender(then-cpo, f, sndr));
+          make-sender(then-cpo, f, sndr))
         
+ + except that `sndr` is evaluated only once. 4. For `then`, `upon_error`, and `upon_stopped`, let `set-cpo` be `set_value`, `set_error`, and `set_stopped` respectively. The @@ -7864,7 +7895,7 @@ namespace std::execution { struct impls-for<decayed-typeof<then-cpo>> : default-impls { static constexpr auto complete = []<class Tag, class... Args> - (auto /*index*/, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void { + (auto, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void { if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) { TRY-SET-VALUE(std::move(rcvr), invoke(std::move(fn), std::forward<Args>(args)...)); @@ -7880,8 +7911,8 @@ namespace std::execution { unless it returns a sender `out_sndr` that: 1. Invokes `f` or a copy of such with the value, error, or stopped result - datums of `sndr` (for `then`, `upon_error`, and `upon_stopped` - respectively), using the result value of `f` as `out_sndr`'s value + datums of `sndr` for `then`, `upon_error`, and `upon_stopped` + respectively, using the result value of `f` as `out_sndr`'s value completion, and 2. Forwards all other completion operations unchanged. @@ -7893,10 +7924,10 @@ namespace std::execution { operation by passing the sender's result datums to a user-specified callable, which returns a new sender that is connected and started. -2. Let the expression `let-cpo` be one of `let_value`, - `let_error`, or `let_stopped` and let `set-cpo` be the - completion function that corresponds to `let-cpo` - (`set_value` for `let_value`, etc.). For a subexpression `sndr`, let +2. For `let_value`, `let_error`, and `let_stopped`, let `set-cpo` + be `set_value`, `set_error`, and `set_stopped` respectively. + Let the expression `let-cpo` be one of `let_value`, + `let_error`, or `let_stopped`. For a subexpression `sndr`, let let-env(sndr) be expression-equivalent to the first well-formed expression below: @@ -7904,12 +7935,12 @@ namespace std::execution { - MAKE-ENV(get_domain, get_domain(get_env(sndr))) - - `empty_env{}` + - `(void(sndr), empty_env{})` 3. The names `let_value`, `let_error`, and `let_stopped` denote customization - point objects. For subexpressions `sndr` and `f`, let `Sndr` be `decltype((sndr))`, - let `F` be the decayed type of `f`. If `Sndr` does not satisfy `sender` or if `F` - does not satisfy `movable-value`, the expression + point objects. For subexpressions `sndr` and `f`, let `F` be the decayed + type of `f`. If `decltype(sndr)` does not satisfy `sender` or if + `decltype(f)` does not satisfy `movable-value`, the expression let-cpo(sndr, f) is ill-formed. If `F` does not satisfy `invocable`, the expression `let_stopped(sndr, f)` is ill-formed. @@ -7919,9 +7950,11 @@ namespace std::execution {
       transform_sender(
         get-domain-early(sndr),
-        make-sender(let-cpo, f, sndr));
+        make-sender(let-cpo, f, sndr))
       
+ except that `sndr` is evaluated only once. + 5. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `let-cpo` as follows: @@ -7944,38 +7977,51 @@ namespace std::execution {
             namespace std::execution {
               template<class Rcvr, class Env>
-              struct receiver2 : Rcvr {
-                explicit receiver2(Rcvr rcvr, Env env)
-                  : Rcvr(std::move(rcvr)), env(std::move(env)) {}
+              struct receiver2 {
+                using receiver_concept = receiver_t;
+
+                template<class... Args>
+                void set_value(Args&&... args) && noexcept {
+                  execution::set_value(std::move(rcvr), std::forward<Args>(args)...);
+                }
+
+                template<class Error>
+                void set_error(Error&& err) && noexcept {
+                  execution::set_error(std::move(rcvr), std::forward<Error>(err));
+                }
+
+                void set_stopped() && noexcept {
+                  execution::set_stopped(std::move(rcvr));
+                }
 
-                auto get_env() const noexcept {
-                  const Rcvr& rcvr = *this;
+                decltype(auto) get_env() const noexcept {
                   return JOIN-ENV(env, FWD-ENV(execution::get_env(rcvr)));
                 }
 
+                Rcvr& rcvr; // exposition only
                 Env env; // exposition only
               };
             }
             
2. impls-for<decayed-typeof<let-cpo>>::get-state is - is initialized with a callable object equivalent to the following: + initialized with a callable object equivalent to the following:
             []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) requires see below {
-              auto&& [tag, data, child] = std::forward<Sndr>(sndr);
-              return [&]<class Fn, class Env>(Fn fn, Env env) {
-                using args-variant-type = see below;
-                using ops2-variant-type = see below;
-
-                struct state-type {
-                  Fn fn;
-                  Env env;
-                  args-variant-type args;
-                  ops2-variant-type ops2;
-                };
-                return state-type{std::move(fn), std::move(env), {}, {}};
-              }(std::forward_like<Sndr>(data), let-env(child));
+              auto& [_, fn, child] = sndr;
+              using fn-t = decay_t<decltype(fn)>;
+              using env-t = decltype(let-env(child));
+              using args-variant-type = see below;
+              using ops2-variant-type = see below;
+
+              struct state-type {
+                Fn fn;
+                Env env;
+                args-variant-type args;
+                ops2-variant-type ops2;
+              };
+              return state-type{std::forward_like<Sndr>(fn), let-env(child), {}, {}};
             }
             
@@ -7988,7 +8034,7 @@ namespace std::execution { as-tuple<Tag(Args...)> denotes the type decayed-tuple<Args...>. Then `args-variant-type` denotes the type variant<monostate, - as-tuple<LetSigs>...>. + as-tuple<LetSigs>...> except with duplicate types removed. 2. Let `as-sndr2` be an alias template such that as-sndr2<Tag(Args...)> denotes the type @@ -7996,21 +8042,22 @@ namespace std::execution { Then `ops2-variant-type` denotes the type variant<monostate, connect_result_t<as-sndr2<LetSigs>, - receiver2<Rcvr, Env>>...>. + receiver2<Rcvr, Env>>...> except with duplicate types removed. 3. The requires-clause constraining the above lambda is satisfied if and only if the types `args-variant-type` and `ops2-variant-type` are well-formed. - 3. The exposition-only function template `let-bind` is equal to: + 3. The exposition-only function template `let-bind` has effects equivalent to:
-            auto& args = state.args.emplace<decayed-tuple<Args...>>(std::forward<Args>(args)...);
-            auto sndr2 = apply(std::move(state.fn), args);
-            auto rcvr2 = receiver2{std::move(rcvr), std::move(state.env)};
-            auto mkop2 = [&] { return connect(std::move(sndr2), std::move(rcvr2)); };
-            auto& op2 = state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2});
-            start(op2);
+            using args_t = decayed-tuple<Args...>;
+            auto mkop2 = [&] {
+              return connect(
+                apply(std::move(state.fn), state.args.emplace<args_t>(std::forward<Args>(args)...)),
+                receiver2{rcvr, std::move(state.env)});
+            };
+            start(state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2}));
             
4. impls-for<decayed-typeof<let-cpo>>::complete is @@ -8034,7 +8081,7 @@ namespace std::execution { JOIN-ENV(let-env(sndr), FWD-ENV(env)). 7. Let the subexpression `out_sndr` denote the result of the invocation - let-cpo(sndr, f) or an object copied or moved from such, + let-cpo(sndr, f) or an object equal to such, and let the subexpression `rcvr` denote a receiver such that the expression `connect(out_sndr, rcvr)` is well-formed. The expression `connect(out_sndr, rcvr)` has undefined behavior unless it creates an asynchronous operation @@ -8053,21 +8100,22 @@ namespace std::execution { 1. `bulk` runs a task repeatedly for every index in an index space. 2. The name `bulk` denotes a customization point object. For subexpressions - `sndr`, `shape`, and `f`, let `Sndr` be `decltype((sndr))`, let `Shape` be - the decayed type of `shape`, and let `F` be the decayed type of `f`. If - `Sndr` does not satisfy `sender`, or if `Shape` does not satisfy `integral`, - or if `F` does not satisfy `movable-value`, bulk(sndr, - shape, f) is ill-formed. + `sndr`, `shape`, and `f`, let `Shape` be `decltype(auto(shape))`. If + `decltype((sndr))` does not satisfy `sender`, or if `Shape` does not + satisfy `integral`, or if `decltype((f))` does not satisfy `movable-value`, + `bulk(sndr, shape, f)` is ill-formed. -3. Otherwise, the expression bulk(sndr, shape, f) is +3. Otherwise, the expression `bulk(sndr, shape, f)` is expression-equivalent to:
         transform_sender(
           get-domain-early(sndr),
-          make-sender(bulk, product-type{shape, f}, sndr));
+          make-sender(bulk, product-type{shape, f}, sndr))
         
+ except that `sndr` is evaluated only once. + 4. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `bulk_t` as follows: @@ -8090,7 +8138,7 @@ namespace std::execution { auto& [shape, f] = state; constexpr bool nothrow = noexcept(f(auto(shape), args...)); TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) { - for (auto max = shape, i = 0; i < max; ++i) { + for (decltype(auto(shape)) i = 0; i < shape; ++i) { f(auto(i), args...); } Tag()(std::move(rcvr), std::forward<Args>(args)...); @@ -8106,7 +8154,7 @@ namespace std::execution { or if the expression `f(auto(shape), args...)` is well-formed. 5. Let the subexpression `out_sndr` denote the result of the invocation - bulk(sndr, shape, f) or an object copied or moved from such, + `bulk(sndr, shape, f)` or an object equal to such, and let the subexpression `rcvr` denote a receiver such that the expression `connect(out_sndr, rcvr)` is well-formed. The expression `connect(out_sndr, rcvr)` has undefined behavior unless it creates an asynchronous operation @@ -8119,6 +8167,8 @@ namespace std::execution { - propagates all completion operations sent by `sndr`. + + #### `execution::split` and `execution::ensure_started` [exec.split] #### {#spec-execution.senders.adapt.split} 1. `split` adapts an arbitrary sender into a sender that can be connected From adafd742eb342795cbd73ea8b107612bc2f8485c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 26 Jun 2024 08:13:25 -0700 Subject: [PATCH 72/89] integrate P3303R1 --- execution.bs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/execution.bs b/execution.bs index 74f723d..4b61fe6 100644 --- a/execution.bs +++ b/execution.bs @@ -7233,22 +7233,24 @@ namespace std::execution { 1. `get_completion_signatures` is a customization point object. Let `sndr` be an expression such that `decltype((sndr))` is `Sndr`, and let `env` be an - expression such that `decltype((env))` is `Env`. Then - `get_completion_signatures(sndr, env)` is expression-equivalent to + expression such that `decltype((env))` is `Env`. Let `new_sndr` be the + expression transform_sender(decltype(get-domain-late(sndr, + env)){}, sndr, env), and let `NewSndr` be `decltype((new_sndr))`. + Then `get_completion_signatures(sndr, env)` is expression-equivalent to (void(sndr), void(env), CS()) except that `void(sndr)` and `void(env)` are indeterminately sequenced, where `CS` is: - 1. `decltype(sndr.get_completion_signatures(env))` if that + 1. `decltype(new_sndr.get_completion_signatures(env))` if that type is well-formed, - 2. Otherwise, `remove_cvref_t::completion_signatures` if that type is well-formed, + 2. Otherwise, `remove_cvref_t::completion_signatures` if that type is well-formed, - 3. Otherwise, if is-awaitable<Sndr, env-promise<Env>> + 3. Otherwise, if is-awaitable<NewSndr, env-promise<Env>> is `true`, then:
             completion_signatures<
-              SET-VALUE-SIG(await-result-type<Sndr,
+              SET-VALUE-SIG(await-result-type<NewSndr,
                             env-promise<Env>>), // see [exec.snd.concepts]
               set_error_t(exception_ptr),
               set_stopped_t()>
@@ -7274,8 +7276,10 @@ namespace std::execution {
 
 2. The name `connect` denotes a customization point object. For subexpressions
     `sndr` and `rcvr`, let `Sndr` be `decltype((sndr))` and `Rcvr` be
-    `decltype((rcvr))`, and let `DS` and `DR` be `decay_t` and
-    `decay_t`, respectively.
+    `decltype((rcvr))`, let `new_sndr` be the expression
+    transform_sender(decltype(get-domain-late(sndr,
+    get_env(rcvr))){}, sndr, get_env(rcvr)), and let `DS` and `DR` be
+    `decay_t` and `decay_t`, respectively.
 
 3. Let `connect-awaitable-promise` be the following exposition-only class:
 
@@ -7383,12 +7387,12 @@ namespace std::execution {
 6. The expression `connect(sndr, rcvr)` is
     expression-equivalent to:
 
-    1. `sndr.connect(rcvr)` if that expression is well-formed.
+    1. `new_sndr.connect(rcvr)` if that expression is well-formed.
 
         * Mandates: The type of the expression above satisfies
             `operation_state`.
 
-    2. Otherwise, connect-awaitable(sndr, rcvr).
+    2. Otherwise, connect-awaitable(new_sndr, rcvr).
 
     3. *Mandates:* `sender && receiver` is `true`.
 

From fe48ba19dd38b24a3673a170ceba802680c4145d Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Wed, 26 Jun 2024 08:35:36 -0700
Subject: [PATCH 73/89] integrate P3175R3

---
 execution.bs | 327 ++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 261 insertions(+), 66 deletions(-)

diff --git a/execution.bs b/execution.bs
index 4b61fe6..a0e1536 100644
--- a/execution.bs
+++ b/execution.bs
@@ -290,7 +290,7 @@ sender auto async_inclusive_scan(scheduler auto sch,                          //
   partials[0] = init;                                                         // 4
 
   return just(std::move(partials))                                            // 5
-       | transfer(sch)
+       | continues_on(sch)
        | bulk(tile_count,                                                     // 6
            [ = ](std::size_t i, std::vector& partials) {              // 7
              auto start = i * tile_size;                                      // 8
@@ -333,7 +333,7 @@ This example builds an asynchronous computation of an inclusive scan:
     we'll do with a `std::vector`, `partials`. We need one `double` of temporary
     storage for each execution agent we create.
 5. Next we'll create our initial sender with [[#design-sender-factory-just]] and
-    [[#design-sender-adaptor-transfer]]. These senders will send the temporary
+    [[#design-sender-adaptor-continues_on]]. These senders will send the temporary
     storage, which we've moved into the sender. The sender has a completion
     scheduler of `sch`, which means the next item in the chain will use `sch`.
 6. Senders and sender adaptors support composition via `operator|`, similar to
@@ -1173,7 +1173,7 @@ any of these steps to be completely asynchronous; the overall flow doesn't care.
 Regardless of the execution resource in which the steps, or part of the steps
 are executed in, the flow is still the same.
 
-### Moving between execution resources with `execution::on` and `execution::transfer` ### {#example-server-on}
+### Moving between execution resources with `execution::starts_on` and `execution::continues_on` ### {#example-server-on}
 
 Example context:
 - reading data from the socket before processing the request
@@ -1182,7 +1182,7 @@ Example context:
 
 Goals:
 - show how one can change the execution resource
-- exemplify the use of `on` and `transfer` algorithms
+- exemplify the use of `starts_on` and `continues_on` algorithms
 
 ```c++
 namespace stdexec = std::execution;
@@ -1198,9 +1198,9 @@ auto snd_read = stdexec::just(sock, buf, buf_len)
 // The entire flow
 auto snd =
     // start by reading data on the I/O thread
-    stdexec::on(io_sched, std::move(snd_read))
+    stdexec::starts_on(io_sched, std::move(snd_read))
     // do the processing on the worker threads pool
-    | stdexec::transfer(work_sched)
+    | stdexec::continues_on(work_sched)
     // process the incoming data (on worker threads)
     | stdexec::then([buf](int read_len) { process_read_data(buf, read_len); })
     // done
@@ -1217,19 +1217,19 @@ reasons, the reading from the socket needs to be done on the I/O thread, and all
 the processing needs to happen on a work-specific execution resource (i.e.,
 thread pool).
 
-Calling `execution::on` will ensure that the given sender will be started on the
+Calling `execution::starts_on` will ensure that the given sender will be started on the
 given scheduler. In our example, `snd_read` is going to be started on the I/O
 scheduler. This sender will just call the legacy code.
 
 The completion-signal will be issued in the I/O execution resource, so we have
 to move it to the work thread pool. This is achieved with the help of the
-`execution::transfer` algorithm. The rest of the processing (in our case, the
+`execution::continues_on` algorithm. The rest of the processing (in our case, the
 last call to `then`) will happen in the work thread pool.
 
-The reader should notice the difference between `execution::on` and
-`execution::transfer`. The `execution::on` algorithm will ensure that the given
+The reader should notice the difference between `execution::starts_on` and
+`execution::continues_on`. The `execution::starts_on` algorithm will ensure that the given
 sender will start in the specified context, and doesn't care where the
-completion-signal for that sender is sent. The `execution::transfer` algorithm
+completion-signal for that sender is sent. The `execution::continues_on` algorithm
 will not care where the given sender is going to be started, but will ensure
 that the completion-signal of will be transferred to the given context.
 
@@ -1802,7 +1802,7 @@ ex::sender auto task =
     ex::get_scheduler(), // Fetches scheduler from receiver.
     [](auto current_sched) {
       // Lauch some nested work on the current scheduler:
-      return ex::on(current_sched, nested work...);
+      return ex::starts_on(current_sched, nested work...);
     });
 
 std::this_thread::sync_wait(std::move(task));
@@ -1951,7 +1951,7 @@ The changes since R2 are as follows:
 
 Fixes:
 
-* Fix specification of the `on` algorithm to clarify lifetimes of intermediate
+* Fix specification of the `starts_on` algorithm to clarify lifetimes of intermediate
     operation states and properly scope the `get_scheduler` query.
 * Fix a memory safety bug in the implementation of
     `connect-awaitable`.
@@ -2186,7 +2186,7 @@ parallel runtimes, such as task frameworks (like
 \[HPX](https://github.com/STEllAR-GROUP/hpx)) or accelerator runtimes (like CUDA
 or SYCL).
 
-Therefore, in addition to the `on` sender algorithm from [[P1897R3]], we are
+Therefore, in addition to the `starts_on` sender algorithm from [[P1897R3]], we are
 proposing a way for senders to advertise what scheduler (and by extension what
 execution resource) they will complete on. Any given sender may have
 [=completion schedulers=] for some or all of the signals (value, error, or
@@ -2222,7 +2222,7 @@ execution::scheduler auto completion_sch1 =
   execution::get_completion_scheduler<execution::set_value_t>(get_env(snd1));
 // completion_sch1 is equivalent to cpu_sched
 
-execution::sender auto snd2 = execution::transfer(snd1, gpu_sched);
+execution::sender auto snd2 = execution::continues_on(snd1, gpu_sched);
 execution::sender auto snd3 = execution::then(snd2, []{
     std::cout << "I am running on gpu_sched!\n";
 });
@@ -2245,7 +2245,7 @@ We propose that, for senders advertising their [=completion scheduler=], all
 execution resource transitions must be explicit; running user code
 anywhere but where they defined it to run must be considered a bug.
 
-The `execution::transfer` sender adaptor performs a transition from one
+The `execution::continues_on` sender adaptor performs a transition from one
 execution resource to another:
 
 
@@ -2257,7 +2257,7 @@ execution::sender auto then1 = execution::then(snd1, []{
     std::cout << "I am running on sch1!\n";
 });
 
-execution::sender auto snd2 = execution::transfer(then1, sch2);
+execution::sender auto snd2 = execution::continues_on(then1, sch2);
 execution::sender auto then2 = execution::then(snd2, []{
     std::cout << "I am running on sch2!\n";
 });
@@ -2778,9 +2778,9 @@ then back on the CPU thread pool:
 Function call 
(nested)
 auto snd = execution::then(
-             execution::transfer(
+             execution::continues_on(
                execution::then(
-                 execution::transfer(
+                 execution::continues_on(
                    execution::then(
                      execution::schedule(thread_pool.scheduler())
                      []{ return 123; }),
@@ -2796,9 +2796,9 @@ auto [result] = this_thread::sync_wait(snd).value();
 
 auto snd0 = execution::schedule(thread_pool.scheduler());
 auto snd1 = execution::then(snd0, []{ return 123; });
-auto snd2 = execution::transfer(snd1, cuda::new_stream_scheduler());
+auto snd2 = execution::continues_on(snd1, cuda::new_stream_scheduler());
 auto snd3 = execution::then(snd2, [](int i){ return 123 * 5; })
-auto snd4 = execution::transfer(snd3, thread_pool.scheduler())
+auto snd4 = execution::continues_on(snd3, thread_pool.scheduler())
 auto snd5 = execution::then(snd4, [](int i){ return i - 5; });
 auto [result] = *this_thread::sync_wait(snd4);
 // result == 610
@@ -2808,9 +2808,9 @@ auto [result] = *this_thread::sync_wait(snd4);
 
 auto snd = execution::schedule(thread_pool.scheduler())
          | execution::then([]{ return 123; })
-         | execution::transfer(cuda::new_stream_scheduler())
+         | execution::continues_on(cuda::new_stream_scheduler())
          | execution::then([](int i){ return 123 * 5; })
-         | execution::transfer(thread_pool.scheduler())
+         | execution::continues_on(thread_pool.scheduler())
          | execution::then([](int i){ return i - 5; });
 auto [result] = this_thread::sync_wait(snd).value();
 // result == 610
@@ -2825,9 +2825,9 @@ following sender adaptors are not pipeable.
     sender adaptor takes a variadic pack of senders, a partially applied form
     would be ambiguous with a non partially applied form with an arity of one
     less.
-* `execution::on`: This sender adaptor changes how the sender passed to it is
+* `execution::starts_on`: This sender adaptor changes how the sender passed to it is
     executed, not what happens to its result, but allowing it in a pipeline makes
-    it read as if it performed a function more similar to `transfer`.
+    it read as if it performed a function more similar to `continues_on`.
 
 Sender consumers could be made pipeable, but we have chosen to not do so.
 However, since these are terminal nodes in a pipeline and nothing can be piped
@@ -3230,7 +3230,7 @@ onto it.
     execution::sender auto task =
       execution::get_scheduler()
         | execution::let_value([](auto sched) {
-            return execution::on(sched, some nested work here);
+            return execution::starts_on(sched, some nested work here);
         });
 
     this_thread::sync_wait( std::move(task) ); // wait for it to finish
@@ -3258,10 +3258,10 @@ consumers such as [[#design-sender-consumer-start_detached]] and
 For more implementer-centric description of starting senders, see
 [[#design-laziness]].
 
-### `execution::transfer` ### {#design-sender-adaptor-transfer}
+### `execution::continues_on` ### {#design-sender-adaptor-continues_on}
 
 
-execution::sender auto transfer(
+execution::sender auto continues_on(
     execution::sender auto input,
     execution::scheduler auto scheduler
 );
@@ -3278,7 +3278,7 @@ execution::scheduler auto gpu_sched = cuda::scheduler();
 execution::sender auto cpu_task = execution::schedule(cpu_sched);
 // cpu_task describes the creation of a new task on the system thread pool
 
-execution::sender auto gpu_task = execution::transfer(cpu_task, gpu_sched);
+execution::sender auto gpu_task = execution::continues_on(cpu_task, gpu_sched);
 // gpu_task describes the transition of the task graph described by cpu_task to the gpu
 
@@ -3363,10 +3363,10 @@ returned sender is started. works with values sent by the input sender, `let_error` works with errors, and `let_stopped` is invoked when the "stopped" signal is sent. -### `execution::on` ### {#design-sender-adaptor-on} +### `execution::starts_on` ### {#design-sender-adaptor-starts_on}
-execution::sender auto on(
+execution::sender auto starts_on(
     execution::scheduler auto sched,
     execution::sender auto snd
 );
@@ -3816,7 +3816,7 @@ together into a single submission of a GPU kernel.
 
 ## Execution resource transitions are two-step ## {#design-transition-details}
 
-Because `execution::transfer` takes a sender as its first argument, it is not
+Because `execution::continues_on` takes a sender as its first argument, it is not
 actually directly customizable by the target scheduler. This is by design: the
 target scheduler may not know how to transition from a scheduler such as
 a CUDA scheduler; transitioning away from a GPU in an efficient manner requires
@@ -3829,26 +3829,26 @@ any sender can be attached to it.
 
 This, however, is a problem: because customization of sender algorithms must be
 controlled by the scheduler they will run on (see [[#design-customization]]),
-the type of the sender returned from `transfer` must be controllable by the
+the type of the sender returned from `continues_on` must be controllable by the
 target scheduler. Besides, the target scheduler may itself represent a
 specialized execution resource, which requires additional work to be performed
 to transition to it. GPUs and remote node schedulers are once again good
 examples of such schedulers: executing code on their execution resources
 requires making runtime API calls for work submission, and quite possibly for
 the data movement of the values being sent by the input sender passed into
-`transfer`.
+`continues_on`.
 
 To allow for such customization from both ends, we propose the inclusion of a
 secondary transitioning sender adaptor, called `schedule_from`. This adaptor is
 a form of `schedule`, but takes an additional, second argument: the input
 sender. This adaptor is not meant to be invoked manually by the end users; they
-are always supposed to invoke `transfer`, to ensure that both schedulers have a
+are always supposed to invoke `continues_on`, to ensure that both schedulers have a
 say in how the transitions are made. Any scheduler that specializes
-`transfer(snd, sch)` shall ensure that the return value of their customization
+`continues_on(snd, sch)` shall ensure that the return value of their customization
 is equivalent to `schedule_from(sch, snd2)`, where `snd2` is a successor of
 `snd` that sends values equivalent to those sent by `snd`.
 
-The default implementation of `transfer(snd, sched)` is `schedule_from(sched,
+The default implementation of `continues_on(snd, sched)` is `schedule_from(sched,
 snd)`.
 
 ## All senders are typed ## {#design-typed}
@@ -5326,7 +5326,7 @@ template<class Initializer>
     
         
  • sender factories (e.g., `schedule`, `just`, `read`)
  • -
  • sender adaptors (e.g., `transfer`, `then`, `let_value`)
  • +
  • sender adaptors (e.g., `continues_on`, `then`, `let_value`)
  • sender consumers (e.g., `start_detached`, `sync_wait`)
@@ -5809,8 +5809,9 @@ namespace std::execution { template<class-type D> struct sender_adaptor_closure { }; + struct starts_on_t { see below }; + struct continues_on_t { see below }; struct on_t { see below }; - struct transfer_t { see below }; struct schedule_from_t { see below }; struct then_t { see below }; struct upon_error_t { see below }; @@ -5827,8 +5828,9 @@ namespace std::execution { struct stopped_as_optional_t { see below }; struct stopped_as_error_t { see below }; + inline constexpr starts_on_t starts_on{}; + inline constexpr continues_on_t continues_on{}; inline constexpr on_t on{}; - inline constexpr transfer_t transfer{}; inline constexpr schedule_from_t schedule_from{}; inline constexpr then_t then{}; inline constexpr upon_error_t upon_error{}; @@ -6488,13 +6490,13 @@ namespace std::execution { }();
- The `transfer` algorithm works in tandem + The `continues_on` algorithm works in tandem with `schedule_from` ([exec.schedule.from])) to give scheduler authors a way to customize both how to transition onto - (`transfer`) and off of (`schedule_from`) a given execution - context. Thus, `transfer` ignores the domain of the predecessor + (`continues_on`) and off of (`schedule_from`) a given execution + context. Thus, `continues_on` ignores the domain of the predecessor and uses the domain of the destination scheduler to select a - customization, a property that is unique to `transfer`. That is + customization, a property that is unique to `continues_on`. That is why it is given special treatment here. - Otherwise, return Domain(); where `Domain` is @@ -6863,6 +6865,34 @@ namespace std::execution { completion-signatures-for<Sndr, Env> to communicate to users why. + 15.
+        template<sender Sndr, queryable Env>
+          constexpr auto write-env(Sndr&& sndr, Env&& env); // exposition only
+        
+ + 1. `write-env` is an exposition-only sender adaptor that, when + connected with a receiver `rcvr`, connects the adapted sender with a + receiver whose execution environment is the result of joining the + `queryable` argument `env` to the result of `get_env(rcvr)`. + + 2. Let `write-env-t` be an exposition-only empty class type. + + 3. *Returns:* make-sender(make-env-t(), std::forward<Env>(env), std::forward<Sndr>(sndr)). + + 4. *Remarks:* The exposition-only class template + `impls-for` ([exec.snd.general]) is specialized for + `write-env-t` as follows: + +
+            template<>
+            struct impls-for<write-env-t> : default-impls {
+              static constexpr auto get-env =
+                [](auto, const auto& state, const auto& rcvr) noexcept {
+                  return JOIN-ENV(state, get_env(rcvr));
+                };
+            };
+            
+ ### Sender concepts [exec.snd.concepts] ### {#spec-execution.snd.concepts} 1. The `sender` concept defines the requirements for a sender type @@ -7592,38 +7622,38 @@ namespace std::execution { initializations of the bound argument entities of the result, as specified above, are all well-formed. -#### `execution::on` [exec.on] #### {#spec-execution.senders.adapt.on} +#### `execution::starts_on` [exec.starts.on] #### {#spec-execution.senders.adapt.starts.on} -1. `on` adapts an input sender into a sender that will start on an execution +1. `starts_on` adapts an input sender into a sender that will start on an execution agent belonging to a particular scheduler's associated execution resource. -2. The name `on` denotes a customization point object. For subexpressions +2. The name `starts_on` denotes a customization point object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or - `decltype((sndr))` does not satisfy `sender`, `on(sch, sndr)` is ill-formed. + `decltype((sndr))` does not satisfy `sender`, `starts_on(sch, sndr)` is ill-formed. -3. Otherwise, the expression `on(sch, sndr)` is expression-equivalent to: +3. Otherwise, the expression `starts_on(sch, sndr)` is expression-equivalent to:
         transform_sender(
           query-or-default(get_domain, sch, default_domain()),
-          make-sender(on, sch, sndr))
+          make-sender(starts_on, sch, sndr))
         
except that `sch` is evaluated only once. 4. Let `out_sndr` and `env` be subexpressions such that `OutSndr` is `decltype((out_sndr))`. If - sender-for<OutSndr, on_t> is `false`, then the expressions - `on.transform_env(out_sndr, env)` and `on.transform_sender(out_sndr, env)` are ill-formed; + sender-for<OutSndr, starts_on_t> is `false`, then the expressions + `starts_on.transform_env(out_sndr, env)` and `starts_on.transform_sender(out_sndr, env)` are ill-formed; otherwise: - - `on.transform_env(out_sndr, env)` is equivalent to: + - `starts_on.transform_env(out_sndr, env)` is equivalent to:
             auto&& [_, sch, _] = out_sndr;
             return JOIN-ENV(SCHED-ENV(sch), FWD-ENV(env));
             
- - `on.transform_sender(out_sndr, env)` is equivalent to: + - `starts_on.transform_sender(out_sndr, env)` is equivalent to:
             auto&& [_, sch, sndr] = out_sndr;
@@ -7635,7 +7665,7 @@ namespace std::execution {
               });
             
-5. Let `out_sndr` be a subexpression denoting a sender returned from `on(sch, sndr)` +5. Let `out_sndr` be a subexpression denoting a sender returned from `starts_on(sch, sndr)` or one equal to such, and let `OutSndr` be the type `decltype((out_sndr))`. Let `out_rcvr` be a subexpression denoting a receiver that has an environment of type `Env` such that `sender_in` is `true`. Let `op` be an lvalue @@ -7644,21 +7674,21 @@ namespace std::execution { associated execution resource of `sch`. If scheduling onto `sch` fails, an error completion on `out_rcvr` shall be executed on an unspecified execution agent. -#### `execution::transfer` [exec.transfer] #### {#spec-execution.senders.adapt.transfer} +#### `execution::continues_on` [exec.continues.on] #### {#spec-execution.senders.adapt.continues.on} -1. `transfer` adapts a sender into one that completes on the specified scheduler. +1. `continues_on` adapts a sender into one that completes on the specified scheduler. -2. The name `transfer` denotes a customization point object. For +2. The name `continues_on` denotes a customization point object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, - `transfer(sndr, sch)` is ill-formed. + `continues_on(sndr, sch)` is ill-formed. -3. Otherwise, the expression `transfer(sndr, sch)` is expression-equivalent to: +3. Otherwise, the expression `continues_on(sndr, sch)` is expression-equivalent to:
         transform_sender(
           get-domain-early(sndr),
-          make-sender(transfer, sch, sndr))
+          make-sender(continues_on, sch, sndr))
         
except that `sndr` is evaluated only once. @@ -7680,7 +7710,7 @@ namespace std::execution { 5. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If sender-for<Sndr, transfer_t> is `false`, then the expression - `transfer.transform_sender(sndr, env)` is ill-formed; otherwise, it + `continues_on.transform_sender(sndr, env)` is ill-formed; otherwise, it is equal to:
@@ -7688,12 +7718,12 @@ namespace std::execution {
         return schedule_from(std::move(data), std::move(child));
         
- This causes the `transfer(sndr, sch)` sender to become + This causes the `continues_on(sndr, sch)` sender to become `schedule_from(sch, sndr)` when it is connected with a receiver whose - execution domain does not customize `transfer`. + execution domain does not customize `continues_on`. 6. Let `out_sndr` be a subexpression denoting a sender returned from - `transfer(sndr, sch)` or one equal to such, and let `OutSndr` be the type + `continues_on(sndr, sch)` or one equal to such, and let `OutSndr` be the type `decltype((out_sndr))`. Let `out_rcvr` be a subexpression denoting a receiver that has an environment of type `Env` such that `sender_in` is `true`. Let `op` be an lvalue referring to the operation state that @@ -7708,7 +7738,7 @@ namespace std::execution { 1. `schedule_from` schedules work dependent on the completion of a sender onto a scheduler's associated execution resource. `schedule_from` is not meant to be used in user code; it is - used in the implementation of `transfer`. + used in the implementation of `continues_on`.
2. The name `schedule_from` denotes a customization point object. For some subexpressions `sch` and `sndr`, let `Sch` be `decltype((sch))` and `Sndr` be @@ -7863,6 +7893,171 @@ namespace std::execution { associated with `sch`. If scheduling onto `sch` fails, an error completion on `out_rcvr` shall be executed on an unspecified execution agent. +#### `execution::on` [exec.on] #### {#spec-execution.senders.adaptors.on} + +1. The `on` sender adaptor has two forms: + + - `on(sch, sndr)`, which starts a sender `sndr` on an execution agent + belonging to a scheduler `sch`'s associated execution resource and that, + upon `sndr`'s completion, transfers execution back to the execution + resource on which the `on` sender was started. + + - `on(sndr, sch, closure)`, which upon completion of a sender `sndr`, + transfers execution to an execution agent belonging to a scheduler `sch`'s + associated execution resource, then executes a sender adaptor closure + `closure` with the async results of the sender, and that then transfers + execution back to the execution resource on which `sndr` completed. + +2. The name `on` denotes a customization point object. For some subexpressions + `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or + `decltype((sndr))` does not satisfy `sender`, `on(sch, sndr)` is ill-formed. + +3. Otherwise, the expression `on(sch, sndr)` is expression-equivalent to: + +
+    transform_sender(
+      query-or-default(get_domain, sch, default_domain()),
+      make-sender(on, sch, sndr));
+    
+ +4. For a subexpression `closure`, if `decltype((closure))` is not a sender + adaptor closure object ([exec.adapt.objects]), the expression `on(sndr, sch, + closure)` is ill-formed; otherwise, it is expression-equivalent to: + +
+    transform_sender(
+      get-domain-early(sndr),
+      make-sender(on, pair{sch, closure}, sndr));
+    
+ +5. Let `out_sndr` and `env` be subexpressions, let `OutSndr` be + `decltype((out_sndr))`, and let `Env` be `decltype((env))`. If + sender-for<OutSndr, on_t> is `false`, then the + expressions `on.transform_env(out_sndr, env)` and + `on.transform_sender(out_sndr, env)` are ill-formed; otherwise: + + 1. Let `not-a-scheduler` be an unspecified empty class type, and + let `not-a-sender` be the exposition-only type: + +
+        struct not-a-sender {
+          using sender_concept = sender_t;
+
+          auto get_completion_signatures(auto&&) const {
+            return see below;
+          }
+        };
+        
+ + ... where the member function `get_completion_signatures` returns an + object of a type that is not a specialization of the + `completion_signatures` class template. + + 2. `on.transform_env(out_sndr, env)` is equivalent to: + +
+        auto& [_, data, _] = out_sndr;
+        if constexpr (scheduler<decltype(data)>) {
+          return JOIN-ENV(SCHED-ENV(data), FWD-ENV(std::forward<Env>(env)));
+        } else {
+          return std::forward<Env>(env);
+        }
+        
+ + 3. `on.transform_sender(out_sndr, env)` is equivalent to: + +
+        auto& [_, data, child] = out_sndr;
+        if constexpr (scheduler<decltype(data)>) {
+          auto orig_sch =
+            query-with-default(get_scheduler, env, not-a-scheduler());
+
+          if constexpr (same_as<decltype(orig_sch), not-a-scheduler>) {
+            return not-a-sender{};
+          } else {
+            return continues_on(
+              starts_on(std::forward_like<OutSndr>(data), std::forward_like<OutSndr>(child)),
+              std::move(orig_sch));
+          }
+        } else {
+          auto& [sch, closure] = data;
+          auto orig_sch = query-with-default(
+            get_completion_scheduler<set_value_t>,
+            get_env(child),
+            query-with-default(get_scheduler, env, not-a-scheduler()));
+
+          if constexpr (same_as<decltype(orig_sch), not-a-scheduler>) {
+            return not-a-sender{};
+          } else {
+            return write-env(
+              continues_on(
+                std::forward_like<OutSndr>(closure)(
+                  continues_on(
+                    write-env(std::forward_like<OutSndr>(child), SCHED-ENV(orig_sch)),
+                    sch)),
+                orig_sch),
+              SCHED-ENV(sch));
+          }
+        }
+        
+ + 4. Recommended practice: Implementations should use the return type + of not-a-sender::get_completion_signatures to + inform users that their usage of `on` is incorrect because there is no + available scheduler onto which to restore execution. + +LEWG is uncomfortable with specifying the semantic +requirements of `on` customizations in terms of "semantic equivalence" to the +lowered expressions. LEWG would like to clarify what effects are considered +salient when determining semantic equivalence. The author thinks this is a fair +request but has no recommendataions at present. + +6. Let the subexpression `out_sndr` denote the result of the invocation `on(sch, + sndr)` or an object equal to such, let `OutSndr` be `decltype((out_sndr))`, + let the subexpression `rcvr` denote a receiver such that + `sender_to` is `true`, and let + `sch_copy` and `sndr_copy` be lvalue subexpressions refering to objects + decay-copied from `sch` and `sndr` respectively. + + The expression `connect(out_sndr, rcvr)` has undefined behavior unless it + creates an asynchronous operation as if by calling `connect(S, rcvr)`, where + `S` is a sender expression semantically equivalent to: + +
+    continues_on(
+      starts_on(std::forward_like<OutSndr>(sch_copy), std::forward_like<OutSndr>(sndr_copy)),
+      orig_sch)
+    
+ + where `orig_sch` is `get_scheduler(get_env(rcvr))`. + +7. Let the subexpression `out_sndr2` denote the result of the invocation + `on(sndr, sch, closure)` or an object copied or moved from such, let + `OutSndr2` be `decltype((out_sndr2))`, let the subexpression `rcvr2` denote + a receiver such that `sender_to` + is `true`, and let `sndr_copy`, `sch_copy`, and `closure_copy` be lvalue + subexpressions refering to objects decay-copied from `sndr`, `sch`, and + `closure` respectively. + + The expression `connect(out_sndr2, rcvr2)` has undefined behavior unless it + creates an asynchronous operation as if by calling `connect(S2, rcvr2)`, where + `S2` is a sender expression semantically equivalent to: + +
+    write-env(
+      continues_on(
+        std::forward_like<OutSndr2>(closure_copy)(
+          continues_on(
+            write-env(std::forward_like<OutSndr2>(sndr_copy), SCHED-ENV(orig_sch)),
+            sch_copy)),
+        orig_sch),
+      SCHED-ENV(sch_copy))
+    
+ + where `orig_sch` is an lvalue refering to an object decay-copied from + `get_completion_scheduler(get_env(sndr_copy))` if that + expression is well-formed; otherwise, `get_scheduler(get_env(rcvr2))`. + #### `execution::then`, `execution::upon_error`, `execution::upon_stopped` [exec.then] #### {#spec-execution.senders.adaptor.then} 1. `then` attaches an invocable as a continuation for an input sender's value From 98e6b27f95dadb65b9128f9d395b105154ea7550 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 26 Jun 2024 11:21:20 -0700 Subject: [PATCH 74/89] replace `pair` with `product-type` --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index a0e1536..2fc10ef 100644 --- a/execution.bs +++ b/execution.bs @@ -7927,7 +7927,7 @@ namespace std::execution {
     transform_sender(
       get-domain-early(sndr),
-      make-sender(on, pair{sch, closure}, sndr));
+      make-sender(on, product-type{sch, closure}, sndr));
     
5. Let `out_sndr` and `env` be subexpressions, let `OutSndr` be From a627fb7ebd38a295e06ac6035124b64a2d254842 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 26 Jun 2024 19:05:01 -0700 Subject: [PATCH 75/89] feedback from LWG wording review on 2024-06-26 --- execution.bs | 552 ++++++++++++++++++++++++++------------------------- 1 file changed, 279 insertions(+), 273 deletions(-) diff --git a/execution.bs b/execution.bs index 2fc10ef..f30bf29 100644 --- a/execution.bs +++ b/execution.bs @@ -5726,12 +5726,6 @@ namespace std::execution { template<class... Ts> struct type-list; // exposition only - template<class Sndr, class Env = empty_env> - using single-sender-value-type = see below; // exposition only - - template<class Sndr, class Env = empty_env> - concept single-sender = see below; // exposition only - // [exec.getcomplsigs], completion signatures struct get_completion_signatures_t { see below }; inline constexpr get_completion_signatures_t get_completion_signatures {}; @@ -5763,6 +5757,12 @@ namespace std::execution { requires sender_in<Sndr, Env> inline constexpr bool sends_stopped = see below; + template<class Sndr, class Env> + using single-sender-value-type = see below; // exposition only + + template<class Sndr, class Env> + concept single-sender = see below; // exposition only + template<sender Sndr> using tag_of_t = see below; @@ -5936,6 +5936,35 @@ namespace std::execution { }
+2. For types `Sndr` and `Env`, + single-sender-value-type<Sndr, Env> is + an alias for: + + 1. `value_types_of_t` + if that type is well-formed, + + 2. Otherwise, `void` if `value_types_of_t` + is `variant>` or `variant<>`, + + 3. Otherwise, value_types_of_t<Sndr, Env, decayed-tuple, + type_identity_t> if that type is well-formed, + + 4. Otherwise, single-sender-value-type<Sndr, Env> + is ill-formed. + +3. The exposition-only concept `single-sender` is defined as follows: + +
+    namespace std::execution {
+      template<class Sndr, class Env>
+        concept single-sender =
+          sender_in<Sndr, Env> &&
+          requires {
+            typename single-sender-value-type<Sndr, Env>;
+          };
+    }
+    
+ ## Queries [exec.queries] ## {#spec-execution.queries} ### `forwarding_query` [exec.fwd.env] ### {#spec-execution.forwarding_query} @@ -6404,15 +6433,15 @@ namespace std::execution { expression-equivalent to sch.query(get_domain). 6. For two subexpressions `rcvr` and `expr`, SET-VALUE(rcvr, - expr) is expression-equivalent to `(expr, set_value(rcvr))` if - the type of `expr` is `void`; otherwise, `set_value(rcvr, expr)`. + expr) is expression-equivalent to `(expr, set_value(std::move(rcvr)))` if + the type of `expr` is `void`; otherwise, `set_value(std::move(rcvr), expr)`. TRY-EVAL(rcvr, expr) is equivalent to:
             try {
               expr;
             } catch(...) {
-              set_error(rcvr, current_exception());
+              set_error(std::move(rcvr), current_exception());
             }
             
@@ -6558,11 +6587,16 @@ namespace std::execution { };
- 1. An expression of type + 1. `product-type` is presented here in + pseudo-code form for the sake of exposition. It can be approximated in + standard C++ with a `tuple`-like implementation that takes care + to keep the type structural. + + 2. An expression of type `product-type` is usable as the initializer of a structured binding declaration [dcl.struct.bind]. - 2.
+        3.  
             template<size_t I, class Self>
             constexpr decltype(auto) get(this Self&& self) noexcept;
             
@@ -6574,7 +6608,7 @@ namespace std::execution { return std::forward_like<Self>(ts...\[I]);
- 3.
+        4.  
             template<class Self, class Fn>
             constexpr decltype(auto) apply(this Self&& self, Fn&& fn) noexcept(see below);
             
@@ -6594,7 +6628,7 @@ namespace std::execution { 14.
         template<class Tag, class Data = see below, class... Child>
-          constexpr auto make-sender(Tag, Data&& data, Child&&... child);
+          constexpr auto make-sender(Tag tag, Data&& data, Child&&... child);
         
1. *Mandates:* The following expressions are `true`: @@ -7506,7 +7540,7 @@ namespace std::execution { struct impls-for<decayed-typeof<read>> : default-impls { static constexpr auto start = [](auto query, auto& rcvr) noexcept -> void { - TRY-SET-VALUE(std::move(rcvr), query(get_env(rcvr))); + TRY-SET-VALUE(rcvr, query(get_env(rcvr))); }; }; } @@ -7540,7 +7574,7 @@ namespace std::execution { to connect a child sender has an associated environment equal to FWD-ENV(get_env(rcvr)). - These requirement apply to any function that is selected by the implementation + These requirements apply to any function that is selected by the implementation of the sender adaptor. 4. If a sender returned from a sender adaptor specified in [exec.adapt] is @@ -7678,7 +7712,7 @@ namespace std::execution { 1. `continues_on` adapts a sender into one that completes on the specified scheduler. -2. The name `continues_on` denotes a customization point object. For +2. The name `continues_on` denotes a pipeable sender adaptor object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, `continues_on(sndr, sch)` is ill-formed. @@ -7789,19 +7823,19 @@ namespace std::execution { auto& [_, sch, child] = sndr; - using sched-t = decltype(auto(sch)); - using variant-type = see below; - using receiver-type = see below; - using operation-type = connect_result_t<schedule_result_t<sched-t>, receiver-type>; - constexpr bool nothrow = noexcept(connect(schedule(sch), receiver-type{nullptr})); + using sched_t = decltype(auto(sch)); + using variant_t = see below; + using receiver_t = see below; + using operation_t = connect_result_t<schedule_result_t<sched_t>, receiver_t>; + constexpr bool nothrow = noexcept(connect(schedule(sch), receiver_t{nullptr})); struct state-type { - Rcvr& rcvr; - variant-type async-result; - operation-type op-state; + Rcvr& rcvr; // exposition only + variant_t async-result; // exposition only + operation_t op-state; // exposition only - explicit state-type(sched-t sch, Rcvr& rcvr) noexcept(nothrow) - : rcvr(rcvr), op-state(connect(schedule(sch), receiver-type{this})) {} + explicit state-type(sched_t sch, Rcvr& rcvr) noexcept(nothrow) + : rcvr(rcvr), op-state(connect(schedule(sch), receiver_t{this})) {} }; return state-type{sch, rcvr}; @@ -7813,15 +7847,15 @@ namespace std::execution { 2. Let `Sigs` be a pack of the arguments to the `completion_signatures` specialization named by - `completion_signatures_of_t>`. Let + completion_signatures_of_t<child-type<Sndr>, env_of_t<Rcvr>>. Let `as-tuple` be an alias template that transforms a completion signature `Tag(Args...)` into the `tuple` specialization decayed-tuple<Tag, Args...>. - Then `variant-type` denotes the type + Then `variant_t` denotes the type variant<monostate, as-tuple<Sigs>...>, except with duplicate types removed. - 3. Let `receiver-type` denote the following exposition-only + 3. `receiver_t` is an alias for the following exposition-only class:
@@ -7869,7 +7903,7 @@ namespace std::execution {
             using result_t = decayed-tuple<Tag, Args...>;
             constexpr bool nothrow = is_nothrow_constructible_v<result_t, Tag, Args...>;
 
-            TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) {
+            TRY-EVAL(rcvr, [&]() noexcept(nothrow) {
               state.async-result.template emplace<result_t>(Tag(), std::forward<Args>(args)...);
             }());
 
@@ -8065,10 +8099,10 @@ request but has no recommendataions at present.
     error and stopped completion operations respectively, sending the result
     of the invocable as a value completion.
 
-2. The names `then`, `upon_error`, and `upon_stopped` denote customization point
-    objects. Let the expression `then-cpo` be one of `then`,
+2. The names `then`, `upon_error`, and `upon_stopped` denote pipeable sender
+    adaptor objects. Let the expression `then-cpo` be one of `then`,
     `upon_error`, or `upon_stopped`. For subexpressions `sndr` and `f`, if
-    `decltype(sndr)` does not satisfy `sender`, or `decltype(f)` does not
+    `decltype((sndr))` does not satisfy `sender`, or `decltype((f))` does not
     satisfy `movable-value`,
     then-cpo(sndr, f) is ill-formed.
 
@@ -8096,7 +8130,7 @@ request but has no recommendataions at present.
               []<class Tag, class... Args>
                 (auto, auto& fn, auto& rcvr, Tag, Args&&... args) noexcept -> void {
                   if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) {
-                    TRY-SET-VALUE(std::move(rcvr),
+                    TRY-SET-VALUE(rcvr,
                                   invoke(std::move(fn), std::forward<Args>(args)...));
                   } else {
                     Tag()(std::move(rcvr), std::forward<Args>(args)...);
@@ -8136,10 +8170,10 @@ request but has no recommendataions at present.
 
       - `(void(sndr), empty_env{})`
 
-3. The names `let_value`, `let_error`, and `let_stopped` denote customization
-    point objects. For subexpressions `sndr` and `f`, let `F` be the decayed
-    type of `f`. If `decltype(sndr)` does not satisfy `sender` or if
-    `decltype(f)` does not satisfy `movable-value`, the expression
+3. The names `let_value`, `let_error`, and `let_stopped` denote pipeable sender
+    adaptor objects. For subexpressions `sndr` and `f`, let `F` be the decayed
+    type of `f`. If `decltype((sndr))` does not satisfy `sender` or if
+    `decltype((f))` does not satisfy `movable-value`, the expression
     let-cpo(sndr, f) is ill-formed. If `F` does not satisfy
     `invocable`, the expression `let_stopped(sndr, f)` is ill-formed.
 
@@ -8209,16 +8243,16 @@ request but has no recommendataions at present.
             
             []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) requires see below {
               auto& [_, fn, child] = sndr;
-              using fn-t = decay_t<decltype(fn)>;
-              using env-t = decltype(let-env(child));
-              using args-variant-type = see below;
-              using ops2-variant-type = see below;
+              using fn_t = decay_t<decltype(fn)>;
+              using env_t = decltype(let-env(child));
+              using args_variant_t = see below;
+              using ops2_variant_t = see below;
 
               struct state-type {
-                Fn fn;
-                Env env;
-                args-variant-type args;
-                ops2-variant-type ops2;
+                fn_t fn;    // exposition only
+                env_t env;    // exposition only
+                args_variant_t args;    // exposition only
+                ops2_variant_t ops2;    // exposition only
               };
               return state-type{std::forward_like<Sndr>(fn), let-env(child), {}, {}};
             }
@@ -8232,20 +8266,20 @@ request but has no recommendataions at present.
                 `as-tuple` be an alias template such that
                 as-tuple<Tag(Args...)> denotes the type
                 decayed-tuple<Args...>. Then
-                `args-variant-type` denotes the type variant<monostate,
+                `args_variant_t` denotes the type variant<monostate,
                 as-tuple<LetSigs>...> except with duplicate types removed.
 
-            2. Let `as-sndr2` be an alias template such that
+            2. Given a type `Tag` and a pack `Args`, let `as-sndr2` be an alias template such that
                 as-sndr2<Tag(Args...)> denotes the type
                 call-result-t<Fn, decay_t<Args>&...>.
-                Then `ops2-variant-type` denotes the type
+                Then `ops2_variant_t` denotes the type
                 variant<monostate,
                 connect_result_t<as-sndr2<LetSigs>,
                 receiver2<Rcvr, Env>>...> except with duplicate types removed.
 
             3. The requires-clause constraining the above lambda is
-                satisfied if and only if the types `args-variant-type`
-                and `ops2-variant-type` are well-formed.
+                satisfied if and only if the types `args_variant_t`
+                and `ops2_variant_t` are well-formed.
 
         3. The exposition-only function template `let-bind` has effects equivalent to:
 
@@ -8253,10 +8287,11 @@ request but has no recommendataions at present.
             using args_t = decayed-tuple<Args...>;
             auto mkop2 = [&] {
               return connect(
-                apply(std::move(state.fn), state.args.emplace<args_t>(std::forward<Args>(args)...)),
+                apply(std::move(state.fn),
+                      state.args.template emplace<args_t>(std::forward<Args>(args)...)),
                 receiver2{rcvr, std::move(state.env)});
             };
-            start(state.ops2.emplace<decltype(mkop2())>(emplace-from{mkop2}));
+            start(state.ops2.template emplace<decltype(mkop2())>(emplace-from{mkop2}));
             
4. impls-for<decayed-typeof<let-cpo>>::complete is @@ -8266,7 +8301,7 @@ request but has no recommendataions at present. []<class Tag, class... Args> (auto, auto& state, auto& rcvr, Tag, Args&&... args) noexcept -> void { if constexpr (same_as<Tag, decayed-typeof<set-cpo>>) { - TRY-EVAL(std::move(rcvr), let-bind(state, rcvr, std::forward<Args>(args)...)); + TRY-EVAL(rcvr, let-bind(state, rcvr, std::forward<Args>(args)...)); } else { Tag()(std::move(rcvr), std::forward<Args>(args)...); } @@ -8298,7 +8333,7 @@ request but has no recommendataions at present. 1. `bulk` runs a task repeatedly for every index in an index space. -2. The name `bulk` denotes a customization point object. For subexpressions +2. The name `bulk` denotes a pipeable sender adaptor object. For subexpressions `sndr`, `shape`, and `f`, let `Shape` be `decltype(auto(shape))`. If `decltype((sndr))` does not satisfy `sender`, or if `Shape` does not satisfy `integral`, or if `decltype((f))` does not satisfy `movable-value`, @@ -8336,7 +8371,7 @@ request but has no recommendataions at present. if constexpr (same_as<Tag, set_value_t>) { auto& [shape, f] = state; constexpr bool nothrow = noexcept(f(auto(shape), args...)); - TRY-EVAL(std::move(rcvr), [&]() noexcept(nothrow) { + TRY-EVAL(rcvr, [&]() noexcept(nothrow) { for (decltype(auto(shape)) i = 0; i < shape; ++i) { f(auto(i), args...); } @@ -8366,8 +8401,6 @@ request but has no recommendataions at present. - propagates all completion operations sent by `sndr`. - - #### `execution::split` and `execution::ensure_started` [exec.split] #### {#spec-execution.senders.adapt.split} 1. `split` adapts an arbitrary sender into a sender that can be connected @@ -8378,18 +8411,11 @@ request but has no recommendataions at present. given an instance `env`, the expression `get_stop_token(env)` is well-formed and has type `inplace_stop_token`. -3. The names `split` and `ensure_started` denote customization point objects. +3. The names `split` and `ensure_started` denote pipeable sender adaptor closure objects. Let the expression `shared-cpo` be one of `split` or `ensure_started`. For a subexpression `sndr`, let `Sndr` be - `decltype((sndr))`. If sender_in<Sndr, shared-env> or - `constructible_from>, env_of_t>` is `false`, - shared-cpo(sndr) is ill-formed. - - Although it has not yet been approved by LEWG, there - is a bug in the current wording that makes it impossible to safely copy the - attributes of a sender; it may have reference semantics, leading to a - dangling reference. I am striking this part for now and will bring a fix to - LEWG. + `decltype((sndr))`. If sender_in<Sndr, shared-env> is + `false`, shared-cpo(sndr) is ill-formed. 4. Otherwise, the expression shared-cpo(sndr) is expression-equivalent to: @@ -8397,29 +8423,30 @@ request but has no recommendataions at present.
       transform_sender(
         get-domain-early(sndr),
-        make-sender(shared-cpo, {}, sndr));
+        make-sender(shared-cpo, {}, sndr))
       
+ except that `sndr` is evaluated only once. + - The default implementation of `transform_sender` will have the effect of connecting the sender to a receiver and, in the case of `ensure_started`, calling `start` on the resulting operation state. It will return a sender with a different tag type. -5. Let `local-state` denote the following exposition-only class: +5. Let `local-state` denote the following exposition-only class template:
     namespace std::execution {
-      struct local-state-base {
+      struct local-state-base {          // exposition only
         virtual ~local-state-base() = default;
-        virtual void notify() noexcept = 0;
-        virtual void detach() noexcept = 0;
+        virtual void notify() noexcept = 0; // exposition only
+        virtual void detach() noexcept = 0; // exposition only
       };
 
       template<class Sndr, class Rcvr>
-      struct local-state : local-state-base {
-        using on-stop-request = see below;
-        using on-stop-callback = stop_token_of_t<env_of_t<Rcvr>>::
-                                    template callback_type<on-stop-request>;
+      struct local-state : local-state-base { // exposition only
+        using on-stop-callback =     // exposition only
+          stop_callback_of_t<stop_token_of_t<env_of_t<Rcvr>>, on-stop-request>;
 
         local-state(Sndr&& sndr, Rcvr& rcvr) noexcept;
         ~local-state();
@@ -8427,9 +8454,10 @@ request but has no recommendataions at present.
         void notify() noexcept override;
         void detach() noexcept override;
 
-        optional<on-stop-callback> on_stop;
-        shared-state<Sndr>* sh_state;
-        Rcvr* rcvr;
+      private:
+        optional<on-stop-callback> on_stop; // exposition only
+        shared-state<Sndr>* sh_state; // exposition only
+        Rcvr* rcvr; // exposition only
       };
     }
     
@@ -8440,10 +8468,10 @@ request but has no recommendataions at present. 1. *Effects:* Equivalent to:
-            auto&& [tag, data, child] = std::forward<Sndr>(sndr);
+            auto& [_, data, _] = sndr;
             this->sh_state = data.sh_state.get();
             this->sh_state->inc-ref();
-            this->rcvr = &rcvr;
+            this->rcvr = addressof(rcvr);
             
2.
@@ -8472,7 +8500,6 @@ request but has no recommendataions at present.
                   tupl);
               },
               QUAL(sh_state->result));
-            );
             
where `QUAL` is `std::move` if @@ -8526,7 +8553,7 @@ request but has no recommendataions at present. struct env { // exposition only shared-state<Sndr>* sh-state; // exposition only - inplace_stop_source query(get_stop_token_t) const noexcept { + inplace_stop_token query(get_stop_token_t) const noexcept { return sh-state->stop_src.get_token(); } }; @@ -8535,7 +8562,7 @@ request but has no recommendataions at present. return env{sh_state}; } - shared-state<Sndr>* sh_state; + shared-state<Sndr>* sh_state; // exposition only }; }
@@ -8547,32 +8574,31 @@ request but has no recommendataions at present. namespace std::execution { template<class Sndr> struct shared-state { - using variant-type = see below; - using state-list-type = see below; - using state-flag-type = see below; + using variant-type = see below; // exposition only + using state-list-type = see below; // exposition only explicit shared-state(Sndr&& sndr); - void start-op() noexcept; - void notify() noexcept; - void detach() noexcept; - void inc-ref() noexcept; - void dec-ref() noexcept; - - inplace_stop_source stop_src{}; - variant-type result{}; - state-list-type waiting_states; - state-flag-type completed; - atomic<size_t> ref_count{1}; - connect_result_t<Sndr, shared-receiver<Sndr>> op_state; + void start-op() noexcept; // exposition only + void notify() noexcept; // exposition only + void detach() noexcept; // exposition only + void inc-ref() noexcept; // exposition only + void dec-ref() noexcept; // exposition only + + inplace_stop_source stop_src{}; // exposition only + variant-type result{}; // exposition only + state-list-type waiting_states; // exposition only + atomic<bool> completed{false}; // exposition only + atomic<size_t> ref_count{1}; // exposition only + connect_result_t<Sndr, shared-receiver<Sndr>> op_state; // exposition only }; }
1. Let `Sigs` be a pack of the arguments to the `completion_signatures` specialization named by - `completion_signatures_of_t`. Let `as-tuple` be an - alias template such that + `completion_signatures_of_t`. For type `Tag` and pack `Args`, + let `as-tuple` be an alias template such that as-tuple<Tag(Args...)> denotes the type decayed-tuple<Tag, Args...>. Then `variant-type` denotes the type @@ -8582,8 +8608,6 @@ request but has no recommendataions at present.
2. Let `state-list-type` be a type that stores a list of pointers to `local-state-base` objects and that permits atomic insertion. - Let `state-flag-type` be a type that can be atomically toggled - between `true` and `false`. 3.
           explicit shared-state(Sndr&& sndr);
@@ -8596,7 +8620,7 @@ request but has no recommendataions at present. 4.
           void start-op() noexcept;
- 1. *Effects:* inc-ref(). If + 1. *Effects:* Calls inc-ref(). If `stop_src.stop_requested()` is `true`, calls notify(); otherwise, calls `start(op_state)`. @@ -8608,9 +8632,11 @@ request but has no recommendataions at present. - Sets `completed` to `true`, and - Exchanges `waiting_states` with an empty list, storing the old - value in a local `prior_states`. For each pointer `p` in - `prior_states`, calls p->notify(). - Finally, calls dec-ref(). + value in a local `prior_states`. + + Then, for each pointer `p` in `prior_states`, calls + p->notify(). Finally, calls + dec-ref(). 6.
           void detach() noexcept;
@@ -8632,8 +8658,10 @@ request but has no recommendataions at present. 1. *Effects:* Decrements `ref_count`. If the new value of `ref_count` is `0`, calls `delete this`. - 2. *Synchronization:* If `dec_ref()` does not decrement the `ref_count` to `0` then synchronizes with - the call to `dec_ref()` that decrements `ref_count` to `0`. + + 2. *Synchronization:* If dec-ref() does not decrement + the `ref_count` to `0` then synchronizes with + the call to dec-ref() that decrements `ref_count` to `0`. 8. For each type `split_t` and `ensure_started_t`, there is a different, associated exposition-only implementation tag type, `split-impl-tag` @@ -8643,13 +8671,13 @@ request but has no recommendataions at present. shared-cpo.transform_sender(sndr) is equivalent to:
-      auto&& [tag, data, child] = sndr;
+      auto&& [tag, _, child] = sndr;
       auto* sh_state = new shared-state{std::forward_like<decltype((sndr))>(child)};
       return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
       
where `shared-wrapper` is an exposition-only class that manages the - reference count of the `shared-state` object pointed to by `sh_state`. + reference count of the `shared-state` object pointed to by `sh_state`. `shared-wrapper` models `movable` with move operations nulling out the moved-from object. If `tag` is `split_t`, `shared-wrapper` models `copyable` with copy operations incrementing the reference count by calling @@ -8695,12 +8723,12 @@ request but has no recommendataions at present. void operator()(local-state<Sndr, Rcvr>& state, Rcvr& rcvr) const noexcept;
- 1. *Effects:* + 1. *Effects:* If `state.sh_state->completed` is `true`, calls + state.notify() and returns. Otherwise, + does the following in order: - 1. If `state.sh_state->completed` is `true`, calls - state.notify() and returns. - 2. Otherwise, calls: + 1. Calls:
                 state.on_stop.emplace(
@@ -8708,24 +8736,22 @@ request but has no recommendataions at present.
                   on-stop-request{state.sh_state->stop_src})
                 
- If `shared-impl-tag` is - `ensure-started-impl-tag`, and if - `state.sh_state->stop_src.stop_requested()` - is `true`, calls `set_stopped(std::move(rcvr))` - and returns. + 2. If `shared-impl-tag` is `ensure-started-impl-tag`, + and if `state.sh_state->stop_src.stop_requested()` is `true`, + calls `set_stopped(std::move(rcvr))` and returns. - 3. Then atomically does the following: + 3. Otherwise, atomically does the following: - Inserts `&state` into `state.sh_state->waiting_states`, and - Reads the value of `state.sh_state->completed`. - If the value is `true`, calls state.notify() - and returns. + 4. If the value read from `state.sh_state->completed` is `true`, + calls state.notify() and returns. - 4. If `shared-impl-tag` is `split-impl-tag`, and if - `&state` is the first item added to - `state.sh_state->waiting_states`, calls + 4. Otherwise, if `shared-impl-tag` is + `split-impl-tag`, and if `&state` is the first item added + to `state.sh_state->waiting_states`, calls state.sh_state->start-op(). 10.
Under the following conditions, the results of the @@ -8749,33 +8775,29 @@ request but has no recommendataions at present. concatenates all the input senders' value result datums into its own value completion operation. `when_all_with_variant(sndrs...)` is semantically equivalent to `when_all(into_variant(sndrs)...)`, where `sndrs` is a pack of - subexpressions of sender types. + subexpressions whose types model `sender`. 2. The names `when_all` and `when_all_with_variant` denote customization point - objects. For some subexpressions sndri..., let - Sndri... be - decltype((sndri)).... The expressions - when_all(sndri...) and - when_all_with_variant(sndri...) are ill-formed if + objects. Let `sndrs` be a pack of subexpressions, let `Sndrs` be a pack of + the types `decltype((sndrs))...`, and let `CD` be the type + common_type_t<DOMAIN-OF(sndrs)...>, where + DOMAIN-OF(sndr) is the type of + get-domain-early(sndr). The expressions `when_all(sndrs...)` and + `when_all_with_variant(sndrs...)` are ill-formed if any of the following is true: - * If the number of subexpressions in sndri... is 0, or - - * If any type Sndri does not satisfy `sender`. + * `sizeof...(sndrs)` is 0, or - * If the types of the expressions - get-domain-early(sndri) do not share - a common type ([meta.trans.other]) for all values of `i`. + * `(sender && ...)` is `false`, or - Otherwise, let `CD` be the common type of the input senders' domains. + * `CD` is ill-formed. -3. The expression when_all(sndri...) is - expression-equivalent to: +3. The expression `when_all(sndrs...)` is expression-equivalent to:
       transform_sender(
         CD(),
-        make-sender(when_all, {}, sndr0, ... sndrn-1));
+        make-sender(when_all, {}, sndrs...));
       
4. The exposition-only class template `impls-for` @@ -8800,12 +8822,10 @@ request but has no recommendataions at present.
           [](auto&&, auto&&... child) noexcept {
-            auto domain_fn = []<class... Ds>(Ds...) noexcept { return common_type_t<Ds...>(); };
-            using domain_type = decltype(domain_fn(get-domain-early(child)...));
-            if constexpr (same_as<domain_type, default_domain>) {
+            if constexpr (same_as<CD, default_domain>) {
               return empty_env();
             } else {
-              return MAKE-ENV(get_domain, domain_type());
+              return MAKE-ENV(get_domain, CD());
             }
           }
           
@@ -8826,21 +8846,25 @@ request but has no recommendataions at present. expression:
-          BUG: `apply` isn't constrained
-          []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr)
-            -> decltype(apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr))) {
-            return apply(make-state<Rcvr>{get_env(rcvr)}, std::forward<Sndr>(sndr));
+          []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept(e) -> decltype(e) {
+            return e;
           }
           
- where `make-state` is the following exposition-only class type: + where `e` is the expression: + +
+          std::forward<Sndr>(sndr).apply(make-state<Rcvr>{get_env(rcvr)})
+          
+ + and where `make-state` is the following exposition-only class template:
           template<class Sndr, class Env>
-          concept max-1-sender-in = sender_in<Sndr, Env> &&
+          concept max-1-sender-in = sender_in<Sndr, Env> && // exposition only
             (tuple_size_v<value_types_of_t<Sndr, Env, tuple, tuple>> <= 1);
 
-          enum class disposition { started, error, stopped };
+          enum class disposition { started, error, stopped }; // exposition only
 
           template<class Rcvr>
           struct make-state {
@@ -8850,10 +8874,9 @@ request but has no recommendataions at present.
             auto operator()(auto, auto, Sndrs&&... sndrs) const {
               using values_tuple = see below;
               using errors_variant = see below;
-              using stop_token = stop_token_of_t<env_of_t<Rcvr>>;
-              using stop_callback = stop_token::template callback_type<on-stop-request>;
+              using stop_callback = stop_callback_of_t<stop_token_of_t<env_of_t<Rcvr>>, on-stop-request>;
 
-              struct state {
+              struct state-type {
                 void arrive(Rcvr& rcvr) noexcept {
                   if (0 == --count) {
                     complete(rcvr);
@@ -8862,21 +8885,21 @@ request but has no recommendataions at present.
 
                 void complete(Rcvr& rcvr) noexcept; // see below
 
-                atomic<size_t> count{sizeof...(sndrs)};
-                inplace_stop_source stop_src{};
-                atomic<disposition> disp{disposition::started};
-                errors_variant errors{};
-                values_tuple values{};
-                optional<stop_callback> on_stop{nullopt};
+                atomic<size_t> count{sizeof...(sndrs)};   // exposition only
+                inplace_stop_source stop_src{};   // exposition only
+                atomic<disposition> disp{disposition::started};   // exposition only
+                errors_variant errors{};   // exposition only
+                values_tuple values{};   // exposition only
+                optional<stop_callback> on_stop{nullopt};   // exposition only
               };
 
-              return state{};
+              return state-type{};
             }
           };
           
1. Let copy-fail be `exception_ptr` if decay-copying any of the - input senders' result datums can potentially throw; otherwise, + child senders' result datums can potentially throw; otherwise, `none-such`, where `none-such` is an unspecified empty class type. @@ -8889,7 +8912,7 @@ request but has no recommendataions at present. variant<none-such, copy-fail, Es...> with duplicate types removed, where `Es` is the pack of the decayed types of all the - input senders' possible error result datums. + child senders' possible error result datums. 4. The member void state::complete(Rcvr& rcvr) noexcept behaves as follows: @@ -9003,52 +9026,39 @@ request but has no recommendataions at present. if the expression decayed-tuple<decltype(as)...>{as...} is potentially throwing; otherwise, `o.emplace(as...)`. -5. The expression when_all_with_variant(sndri...) is +5. The expression when_all_with_variant(sndrs...) is expression-equivalent to:
       transform_sender(
         CD(),
-        make-sender(when_all_with_variant, {}, sndr0, ... sndrn-1));
+        make-sender(when_all_with_variant, {}, sndrs...));
       
6. Given subexpressions `sndr` and `env`, if sender-for<decltype((sndr)), when_all_with_variant_t> is `false`, then the expression `when_all_with_variant.transform_sender(sndr, env)` is - ill-formed; otherwise, the body of the `transform_sender` member-function is equivalent to: + ill-formed; otherwise, it is equivalent to:
-        auto [tag, data, ...child] = sndr;
-        return when_all(into_variant(std::move(child))...);
+      auto&& [_, _, ...child] = sndr;
+      return when_all(into_variant(std::forward_like<decltype((sndr))>(child))...);
       
- This causes the `when_all_with_variant(sndr...)` sender - to become `when_all(into_variant(sndr)...)` when it is connected with a - receiver with an execution domain that does not customize - `when_all_with_variant`. + This causes the `when_all_with_variant(sndrs...)` sender + to become `when_all(into_variant(sndrs)...)` when it is connected with a + receiver whose execution domain does not customize `when_all_with_variant`. #### `execution::into_variant` [exec.into.variant] #### {#spec-execution.senders.adapt.into_variant} 1. `into_variant` adapts a sender with multiple value completion signatures into - a sender with just one consisting of a `variant` of `tuple`s. - -2. The template `into-variant-type` computes the type sent by - a sender returned from `into_variant`. + a sender with just one value completion signature consisting of a `variant` of `tuple`s. -
-    namespace std::execution {
-      template<class Sndr, class Env>
-          requires sender_in<Sndr, Env>
-        using into-variant-type =
-          value_types_of_t<Sndr, Env>;
-    }
-    
- -3. The name `into_variant` denotes a customization point object. For a +2. The name `into_variant` denotes a pipeable sender adaptor closure object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If `Sndr` does not satisfy `sender`, `into_variant(sndr)` is ill-formed. -4. Otherwise, the expression `into_variant(sndr)` is expression-equivalent to: +3. Otherwise, the expression `into_variant(sndr)` is expression-equivalent to:
       transform_sender(
@@ -9056,6 +9066,8 @@ request but has no recommendataions at present.
         make-sender(into_variant, {}, sndr))
       
+ except that `sndr` is only evaluated once. + 5. The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for `into_variant` as follows: @@ -9075,7 +9087,7 @@ request but has no recommendataions at present.
           []<class Sndr, class Rcvr>(Sndr&& sndr, Rcvr& rcvr) noexcept
-            -> type_identity<into-variant-type<child-type<Sndr>, env_of_t<Rcvr>>> {
+            -> type_identity<value_types_of_t<child-type<Sndr>, env_of_t<Rcvr>>> {
             return {};
           }
           
@@ -9085,17 +9097,10 @@ request but has no recommendataions at present.
           []<class State, class Rcvr, class Tag, class... Args>(
-              auto, State, Rcvr& rcvr, Tag, Args&&... args) noexcept {
+              auto, State, Rcvr& rcvr, Tag, Args&&... args) noexcept -> void {
             if constexpr (same_as<Tag, set_value_t>) {
               using variant_type = typename State::type;
-              using tuple_type = decayed-tuple<Args...>;
-              try {
-                set_value(std::move(rcvr),
-                          variant_type(tuple_type(std::forward<Args>(args)...)));
-              }
-              catch (...) {
-                set_error(std::move(rcvr), current_exception());
-              }
+              TRY-SET-VALUE(rcvr, variant_type(decayed-tuple<Args...>{std::forward<Args>(args)...}));
             } else {
               Tag()(std::move(rcvr), std::forward<Args>(args)...);
             }
@@ -9105,10 +9110,15 @@ request but has no recommendataions at present.
 
 #### `execution::stopped_as_optional` [exec.stopped.as.optional] #### {#spec-execution.senders.adapt.stopped_as_optional}
 
-1. `stopped_as_optional` maps an input sender's stopped completion operation into the value completion operation as an empty optional. The input sender's value completion operation is also converted into an optional. The result is a sender that never completes with stopped, reporting cancellation by completing with an empty optional.
+1. `stopped_as_optional` maps a sender's stopped completion operation into a
+    value completion operation as an disengaged `optional`. The sender's value
+    completion operation is also converted into an `optional`. The result is a
+    sender that never completes with stopped, reporting cancellation by
+    completing with an disengaged `optional`.
 
-2. The name `stopped_as_optional` denotes a customization point object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`.
-    The expression `stopped_as_optional(sndr)` is expression-equivalent to:
+2. The name `stopped_as_optional` denotes a pipeable sender adaptor closure
+    object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. The
+    expression `stopped_as_optional(sndr)` is expression-equivalent to:
 
     
     transform_sender(
@@ -9116,17 +9126,24 @@ request but has no recommendataions at present.
       make-sender(stopped_as_optional, {}, sndr))
     
-3. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))` and `Env` is `decltype((env))`. - If either sender-for<Sndr, stopped_as_optional_t> or single-sender<Sndr, Env> is `false` - then the expression `stopped_as_optional.transform_sender(sndr, env)` is ill-formed; otherwise, it is equal to: + except that `sndr` is only evaluated once. + +3. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))` + and `Env` is `decltype((env))`. If sender-for<Sndr, + stopped_as_optional_t> is `false`, or if the type + single-sender-value-type<Sndr, Env> is ill-formed or + `void`, then the expression `stopped_as_optional.transform_sender(sndr, + env)` is ill-formed; otherwise, it is equivalent to:
-    auto [tag, data, child] = sndr;
+    auto&& [_, _, child] = sndr;
     using V = single-sender-value-type<Sndr, Env>;
     return let_stopped(
-        then(std::move(child),
-                  []<class T>(T&& t) { return optional(std::forward(t)); }),
-        []() noexcept { return just(optional()); });
+        then(std::forward_like<Sndr>(child),
+             []<class... Ts>(Ts&&... ts) noexcept(is_nothrow_constructible_v<V, Ts...>) {
+               return optional<V>(in_place, std::forward<Ts>(ts)...);
+             }),
+        []() noexcept { return just(optional<V>()); });
     
#### `execution::stopped_as_error` [exec.stopped.as.error] #### {#spec-execution.senders.adapt.stopped_as_error} @@ -9136,7 +9153,12 @@ request but has no recommendataions at present. that never completes with stopped, reporting cancellation by completing with an error. -2. The name `stopped_as_error` denotes a customization point object. For some subexpressions `sndr` and `err`, let `Sndr` be `decltype((sndr))` and let `Err` be `decltype((err))`. If the type `Sndr` does not satisfy `sender` or if the type `Err` doesn't satisfy `movable-value`, `stopped_as_error(sndr, err)` is ill-formed. Otherwise, the expression `stopped_as_error(sndr, err)` is expression-equivalent to: +2. The name `stopped_as_error` denotes a pipeable sender adaptor closure object. + For some subexpressions `sndr` and `err`, let `Sndr` be `decltype((sndr))` + and let `Err` be `decltype((err))`. If the type `Sndr` does not satisfy + `sender` or if the type `Err` doesn't satisfy `movable-value`, + `stopped_as_error(sndr, err)` is ill-formed. Otherwise, the expression + `stopped_as_error(sndr, err)` is expression-equivalent to:
     transform_sender(
@@ -9144,15 +9166,20 @@ request but has no recommendataions at present.
       make-sender(stopped_as_error, err, sndr))
     
+ except that `sndr` is only evaluated once. + 3. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))` and `Env` is `decltype((env))`. If sender-for<Sndr, stopped_as_error_t> is `false`, then the expression - `stopped_as_error.transform_sender(sndr, env)` is ill-formed; otherwise, it is equal to: + `stopped_as_error.transform_sender(sndr, env)` is ill-formed; otherwise, it is equivalent to:
-    auto [tag, data, child] = sndr;
+    auto&& [_, err, child] = sndr;
+    using E = decltype(auto(err));
     return let_stopped(
-        std::move(child),
-        [err = std::move(data)]() mutable { return just_error(std::move(err)); });
+        std::forward_like<Sndr>(child),
+        [err = std::forward_like<Sndr>(err)]() mutable noexcept(is_nothrow_move_constructible_v<E>) {
+          return just_error(std::move(err));
+        });
     
### Sender consumers [exec.consumers] ### {#spec-execution.senders.consumers} @@ -9190,7 +9217,7 @@ request but has no recommendataions at present. template<class Sndr> struct detached-receiver { using receiver_concept = receiver_t; - detached-operation<Sndr>* op; // exposition only + detached-operation<Sndr>* op; // exposition only void set_value() && noexcept { delete op; } void set_error() && noexcept { terminate(); } @@ -9200,7 +9227,7 @@ request but has no recommendataions at present. template<class Sndr> struct detached-operation { - connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only + connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only explicit detached-operation(Sndr&& sndr) : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this})) @@ -9227,17 +9254,22 @@ request but has no recommendataions at present.
     namespace std::this_thread {
       struct sync-wait-env {
-        execution::run_loop* loop; // exposition only
+        execution::run_loop* loop; // exposition only
 
-        auto query(execution::get_scheduler_t) const noexcept { loop->get_scheduler(); }
-        auto query(execution::get_delegation_scheduler_t) const noexcept { loop->get_scheduler(); }
+        auto query(execution::get_scheduler_t) const noexcept {
+          return loop->get_scheduler();
+        }
+
+        auto query(execution::get_delegation_scheduler_t) const noexcept {
+          return loop->get_scheduler();
+        }
       };
     }
     
3. Let `sync-wait-result-type` and `sync-wait-with-variant-result-type` be exposition-only - template aliases defined as follows: + alias templates defined as follows:
     namespace std::this_thread {
@@ -9247,7 +9279,7 @@ request but has no recommendataions at present.
 
       template<execution::sender_in<sync-wait-env> Sndr>
         using sync-wait-with-variant-result-type =
-          optional<execution::into-variant-type<Sndr, sync-wait-env>>; // see [exec.into.variant]
+          optional<execution::value_types_of_t<Sndr, sync-wait-env>>;
     }
     
@@ -9278,13 +9310,13 @@ request but has no recommendataions at present. namespace std::this_thread { template<class Sndr> struct sync-wait-state { // exposition only - execution::run_loop loop; - exception_ptr error; - sync-wait-result-type<Sndr> result; + execution::run_loop loop; // exposition only + exception_ptr error; // exposition only + sync-wait-result-type<Sndr> result; // exposition only }; template<class Sndr> - struct sync-wait-receiver { + struct sync-wait-receiver { // exposition only using receiver_concept = execution::receiver_t; sync-wait-state<Sndr>* state; // exposition only @@ -9296,7 +9328,7 @@ request but has no recommendataions at present. void set_stopped() && noexcept; - sync-wait-env get_env() const noexcept { return {&state->loop}; } + sync-wait-env get_env() const noexcept { return {&state->loop}; } }; }
@@ -9310,11 +9342,11 @@ request but has no recommendataions at present.
             try {
-              state->result.emplace(std::forward<Args>(args)...);
+              state->result.emplace(std::forward<Args>(args)...);
             } catch (...) {
-              state->error = current_exception();
+              state->error = current_exception();
             }
-            state->loop.finish();
+            state->loop.finish();
             
2.
@@ -9325,16 +9357,15 @@ request but has no recommendataions at present.
         1. *Effects:* Equivalent to:
 
             
-            state->error = AS-EXCEPT-PTR(std::forward<Error>(err)); // see [exec.general]
-            state->loop.finish();
+            state->error = AS-EXCEPT-PTR(std::forward<Error>(err)); // see [exec.general]
+            state->loop.finish();
             
3.
-        template<class Error>
         void set_stopped() && noexcept;
         
- 1. *Effects:* Equivalent to state->loop.finish(). + 1. *Effects:* Equivalent to state->loop.finish(). 6. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If @@ -9369,14 +9400,13 @@ request but has no recommendataions at present. 1. For a value completion, the result datums are returned in a `tuple` in an engaged `optional` object. - 2. For an error completion, the result datum is rethrown. + 2. For an error completion, an exception is thrown. 3. For a stopped completion, a disengaged `optional` object is returned. 8. The name `this_thread::sync_wait_with_variant` denotes a customization point - object. For a subexpression `sndr`, let `Sndr` be the type of - `into_variant(sndr)`. If sender_in<Sndr, - sync-wait-env> is `false`, + object. For a subexpression `sndr`, let `Sndr` be `decltype(into_variant(sndr))`. + If sender_in<Sndr, sync-wait-env> is `false`, `this_thread::sync_wait_with_variant(sndr)` is ill-formed. Otherwise, it is expression-equivalent to the following, except `sndr` is evaluated only once: @@ -9392,7 +9422,7 @@ request but has no recommendataions at present. - same_as<decltype(e), sync-wait-with-variant-result-type<Sndr>> is `true`, - where `e` is the expression above. + where `e` is the `apply_sender` expression above. 9. If callable<sync_wait_t, Sndr> is `false`, the expression `sync_wait_with_variant.apply_sender(sndr)` is ill-formed. @@ -9420,7 +9450,7 @@ request but has no recommendataions at present. 1. For a value completion, the result datums are returned in an engaged `optional` object that contains a `variant` of `tuple`s. - 2. For an error completion, the result datum is rethrown. + 2. For an error completion, an exception is thrown. 3. For a stopped completion, a disengaged `optional` object is returned. @@ -9456,9 +9486,10 @@ request but has no recommendataions at present. 2. [Example:
-      class my_sender {
+      struct my_sender {
+        using sender_concept = sender_t;
         using completion_signatures =
-          completion_signatures<
+          execution::completion_signatures<
             set_value_t(),
             set_value_t(int, float),
             set_error_t(exception_ptr),
@@ -9476,7 +9507,7 @@ request but has no recommendataions at present.
      
-- end example] -3. This subclause makes use of the following exposition-only entities: +3. [exec.utils.cmplsigs] makes use of the following exposition-only entities:
     template<class Fn>
@@ -9496,9 +9527,9 @@ request but has no recommendataions at present.
         only if it is a function type with one of the following forms:
 
         * set_value_t(Vs...), where `Vs`
-            is an arbitrary parameter pack.
+            is an parameter pack of object or reference types.
         * set_error_t(Err), where `Err` is
-            an arbitrary type.
+            an object or reference type.
         * `set_stopped_t()`
 
     
@@ -9564,6 +9595,9 @@ request but has no recommendataions at present.
     }
     
+ + + ### `execution::transform_completion_signatures` [exec.utils.tfxcmplsigs] ### {#spec-execution.snd_rec_utils.transform_completion_sigs} 1. `transform_completion_signatures` is an alias template used to transform one @@ -9895,14 +9929,6 @@ void finish();
     namespace std::execution {
-      template<class Sndr, class Env>
-        using single-sender-value-type = see below;
-
-      template<class Sndr, class Env>
-        concept single-sender =
-          sender_in<Sndr, Env> &&
-          requires { typename single-sender-value-type<Sndr, Env>; };
-
       template<class Sndr, class Promise>
         concept awaitable-sender =
           single-sender<Sndr, env_of_t> &&
@@ -9916,26 +9942,6 @@ void finish();
     }
     
- 1. Alias template single-sender-value-type is defined as follows: - - 1. If `value_types_of_t` would have the form - `Variant>`, then - single-sender-value-type<Sndr, Env> is an - alias for type `decay_t`. - - 2. Otherwise, if `value_types_of_t` would - have the form `Variant>` or `Variant<>`, then - single-sender-value-type<Sndr, Env> is an - alias for type `void`. - - 3. Otherwise, if `value_types_of_t` would - have the form `Variant>` where `Ts` is a parameter pack, - then single-sender-value-type<Sndr, Env> is an - alias for type `std::tuple...>`. - - 4. Otherwise, single-sender-value-type<Sndr, Env> - is ill-formed. - 2. The type sender-awaitable<Sndr, Promise> is equivalent to the following: From c28b098984d76b743e6ac8fa8fbdb00abc18a65c Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 26 Jun 2024 19:21:28 -0700 Subject: [PATCH 76/89] more erroneous formatting --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index e48aca8..684b386 100644 --- a/execution.bs +++ b/execution.bs @@ -2625,7 +2625,7 @@ particularly satisfactory: work in some circumstances for some kinds of applications, in general it is also pretty user-hostile; it makes it difficult to reason about the safe destruction of resources used by these eager operations. In general, - detached work necessitates some kind of garbage collection; e.g., + detached work necessitates some kind of garbage collection; e.g., `std::shared_ptr`, to ensure resources are kept alive until the operations complete, and can make clean shutdown nigh impossible. From 4d3e68c40cc97a61c4b9ef933f92f3779ad05442 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Wed, 26 Jun 2024 19:35:47 -0700 Subject: [PATCH 77/89] rename `read` to `read_env` --- execution.bs | 57 +++++++++++++--------------------------------------- 1 file changed, 14 insertions(+), 43 deletions(-) diff --git a/execution.bs b/execution.bs index 4be6918..0b15fb3 100644 --- a/execution.bs +++ b/execution.bs @@ -388,7 +388,7 @@ struct dynamic_buffer { // sender_of auto async_read_array(auto handle) { // 2 return just(dynamic_buffer{}) // 4 | let_value([handle] (dynamic_buffer& buf) { // 5 - return just(std::as_writeable_bytes(std::span(&buf.size, 1)) // 6 + return just(std::as_writeable_bytes(std::span(&buf.size, 1))) // 6 | async_read(handle) // 7 | then( // 8 [&buf] (std::size_t bytes_read) { // 9 @@ -3196,29 +3196,16 @@ execution::sender auto just_stopped(); Returns a sender with no [=completion scheduler|completion schedulers=], which completes immediately by calling the receiver's `set_stopped`. -### `execution::read` ### {#design-sender-factory-read} +### `execution::read_env` ### {#design-sender-factory-read}
-execution::sender auto read(auto tag);
-
-execution::sender auto get_scheduler() {
-  return read(execution::get_scheduler);
-}
-execution::sender auto get_delegation_scheduler() {
-  return read(execution::get_delegation_scheduler);
-}
-execution::sender auto get_allocator() {
-  return read(execution::get_allocator);
-}
-execution::sender auto get_stop_token() {
-  return read(execution::get_stop_token);
-}
+execution::sender auto read_env(auto tag);
 
Returns a sender that reaches into a receiver's environment and pulls out the current value associated with the customization point denoted by `Tag`. It then sends the value read back to the receiver through the value channel. For -instance, `get_scheduler()` (with no arguments) is a sender that asks the +instance, `read_env(get_scheduler)` is a sender that asks the receiver for the currently suggested `scheduler` and passes it to the receiver's `set_value` completion-signal. @@ -3228,7 +3215,7 @@ onto it.
     execution::sender auto task =
-      execution::get_scheduler()
+      execution::read_env(get_scheduler)
         | execution::let_value([](auto sched) {
             return execution::starts_on(sched, some nested work here);
         });
@@ -3237,7 +3224,7 @@ onto it.
     
This code uses the fact that `sync_wait` associates a scheduler with the -receiver that it connects with `task`. `get_scheduler()` reads that scheduler +receiver that it connects with `task`. `read_env(get_scheduler)` reads that scheduler out of the receiver, and passes it to `let_value`'s receiver's `set_value` function, which in turn passes it to the lambda. That lambda returns a new sender that uses the scheduler to schedule some nested work onto `sync_wait`'s @@ -5325,7 +5312,7 @@ template<class Initializer> allow the specialization of the provided sender algorithms
    -
  • sender factories (e.g., `schedule`, `just`, `read`)
  • +
  • sender factories (e.g., `schedule`, `just`, `read_env`)
  • sender adaptors (e.g., `continues_on`, `then`, `let_value`)
  • sender consumers (e.g., `start_detached`, `sync_wait`)
@@ -6001,10 +5988,6 @@ namespace std::execution { 3. `forwarding_query(get_allocator)` is a core constant expression and has value `true`. -4. `get_allocator()` (with no arguments) is expression-equivalent to - `execution::read(get_allocator)` ([exec.read]). - - ### `get_stop_token` [exec.get.stop.token] ### {#spec-execution.get_stop_token} @@ -6024,9 +6007,6 @@ namespace std::execution { 3. `forwarding_query(get_stop_token)` is a core constant expression and has value `true`. -4. `get_stop_token()` (with no arguments) is expression-equivalent to - `execution::read(get_stop_token)` ([exec.read]). - ### `execution::get_env` [exec.get.env] ### {#spec-execution.environment.get_env} 1. `execution::get_env` is a customization point object. For a subexpression @@ -6057,9 +6037,6 @@ namespace std::execution { 3. `forwarding_query(execution::get_domain)` is a core constant expression and has value `true`. -4. `get_domain()` (with no arguments) is expression-equivalent to - `execution::read(get_domain)` ([exec.read]). - ### `execution::get_scheduler` [exec.get.scheduler] ### {#spec-execution.get_scheduler} 1. `get_scheduler` asks a queryable object for its associated scheduler. @@ -6074,9 +6051,6 @@ namespace std::execution { 3. `forwarding_query(execution::get_scheduler)` is a core constant expression and has value `true`. -4. `get_scheduler()` (with no arguments) is expression-equivalent to - `execution::read(get_scheduler)` ([exec.read]). - ### `execution::get_delegation_scheduler` [exec.get.delegation.scheduler] ### {#spec-execution.get_delegation_scheduler} 1. `get_delegation_scheduler` asks a queryable object for a scheduler that can be @@ -6093,9 +6067,6 @@ namespace std::execution { 3. `forwarding_query(execution::get_delegation_scheduler)` is a core constant expression and has value `true`. -4. `get_delegation_scheduler()` (with no arguments) is expression-equivalent to - `execution::read(get_delegation_scheduler)` ([exec.read]). - ### `execution::get_forward_progress_guarantee` [exec.get.forward.progress.guarantee] ### {#spec-execution.get_forward_progress_guarantee}
@@ -7521,23 +7492,23 @@ namespace std::execution {
         }
         
-#### `execution::read` [exec.read] #### {#spec-execution.senders.read} +#### `execution::read_env` [exec.read.env] #### {#spec-execution.senders.read.env} -1. `read` is a sender factory for a sender whose asynchronous operation +1. `read_env` is a sender factory for a sender whose asynchronous operation completes synchronously in its start operation with a value completion result equal to a value read from the receiver's associated environment. -2. `read` is a customization point object. For some query object `q`, - the expression `read(q)` is expression-equivalent to - make-sender(read, q). +2. `read_env` is a customization point object. For some query object `q`, + the expression `read_env(q)` is expression-equivalent to + make-sender(read_env, q). 3. The exposition-only class template `impls-for` ([exec.snd.general]) - is specialized for `read` as follows: + is specialized for `read_env` as follows:
     namespace std::execution {
       template<>
-      struct impls-for<decayed-typeof<read>> : default-impls {
+      struct impls-for<decayed-typeof<read_env>> : default-impls {
         static constexpr auto start =
           [](auto query, auto& rcvr) noexcept -> void {
             TRY-SET-VALUE(rcvr, query(get_env(rcvr)));

From 662ecd496daef1160bf3023ae0cdfd3fb8953f10 Mon Sep 17 00:00:00 2001
From: Eric Niebler 
Date: Thu, 27 Jun 2024 10:29:19 -0700
Subject: [PATCH 78/89] changes from LWG morning session 2024-06-27

---
 execution.bs | 134 +++++++++++++++++++++++++--------------------------
 1 file changed, 67 insertions(+), 67 deletions(-)

diff --git a/execution.bs b/execution.bs
index 0b15fb3..b403591 100644
--- a/execution.bs
+++ b/execution.bs
@@ -6561,7 +6561,8 @@ namespace std::execution {
         1. `product-type` is presented here in
             pseudo-code form for the sake of exposition. It can be approximated in
             standard C++ with a `tuple`-like implementation that takes care
-            to keep the type structural.
+            to keep the type an aggregate that can be used as the initializer of a
+            structured binding declaration.
 
         2. An expression of type
             `product-type` is usable as the initializer of a
@@ -7459,7 +7460,7 @@ namespace std::execution {
 2. The names `just`, `just_error`, and `just_stopped` denote customization
     point objects. Let `just-cpo` be one of `just`,
     `just_error`, or `just_stopped`. For a pack of subexpressions `ts`, let `Ts`
-    be the template parameter pack `decltype((ts))`. The expression
+    be the pack of types `decltype((ts))`. The expression
     just-cpo(ts...) is ill-formed if:
 
         - (movable-value<Ts> &&...) is `false`, or
@@ -8382,7 +8383,7 @@ request but has no recommendataions at present.
     given an instance `env`, the expression `get_stop_token(env)` is well-formed
     and has type `inplace_stop_token`.
 
-3. The names `split` and `ensure_started` denote pipeable sender adaptor closure objects.
+3. The names `split` and `ensure_started` denote pipeable sender adaptor objects.
     Let the expression `shared-cpo` be one of `split` or
     `ensure_started`. For a subexpression `sndr`, let `Sndr` be
     `decltype((sndr))`. If sender_in<Sndr, shared-env> is
@@ -8686,7 +8687,7 @@ request but has no recommendataions at present.
 
     2. The member
         impls-for<shared-impl-tag>::start
-        is initialized with a callable object that has a call operator
+        is initialized with a callable object that has a function call operator
         equivalent to the following:
 
         
@@ -8704,7 +8705,7 @@ request but has no recommendataions at present.
                 
                 state.on_stop.emplace(
                   get_stop_token(get_env(rcvr)),
-                  on-stop-request{state.sh_state->stop_src})
+                  on-stop-request{state.sh_state->stop_src});
                 
2. If `shared-impl-tag` is `ensure-started-impl-tag`, @@ -8713,15 +8714,15 @@ request but has no recommendataions at present. 3. Otherwise, atomically does the following: - - Inserts `&state` into `state.sh_state->waiting_states`, and + - Inserts `addressof(state)` into `state.sh_state->waiting_states`, and - Reads the value of `state.sh_state->completed`. 4. If the value read from `state.sh_state->completed` is `true`, calls state.notify() and returns. - 4. Otherwise, if `shared-impl-tag` is - `split-impl-tag`, and if `&state` is the first item added + 5. Otherwise, if `shared-impl-tag` is + `split-impl-tag`, and if `addressof(state)` is the first item added to `state.sh_state->waiting_states`, calls state.sh_state->start-op(). @@ -8751,9 +8752,8 @@ request but has no recommendataions at present. 2. The names `when_all` and `when_all_with_variant` denote customization point objects. Let `sndrs` be a pack of subexpressions, let `Sndrs` be a pack of the types `decltype((sndrs))...`, and let `CD` be the type - common_type_t<DOMAIN-OF(sndrs)...>, where - DOMAIN-OF(sndr) is the type of - get-domain-early(sndr). The expressions `when_all(sndrs...)` and + common_type_t<decltype(get-domain-early(sndrs))...>. + The expressions `when_all(sndrs...)` and `when_all_with_variant(sndrs...)` are ill-formed if any of the following is true: @@ -8768,7 +8768,7 @@ request but has no recommendataions at present.
       transform_sender(
         CD(),
-        make-sender(when_all, {}, sndrs...));
+        make-sender(when_all, {}, sndrs...))
       
4. The exposition-only class template `impls-for` @@ -8823,9 +8823,9 @@ request but has no recommendataions at present.
where `e` is the expression: - +
-          std::forward<Sndr>(sndr).apply(make-state<Rcvr>{get_env(rcvr)})
+          std::forward<Sndr>(sndr).apply(make-state<Rcvr>())
           
and where `make-state` is the following exposition-only class template: @@ -8839,8 +8839,6 @@ request but has no recommendataions at present. template<class Rcvr> struct make-state { - const env_of_t<Rcvr>& env; - template<max-1-sender-in<env_of_t<Rcvr>>... Sndrs> auto operator()(auto, auto, Sndrs&&... sndrs) const { using values_tuple = see below; @@ -9025,7 +9023,7 @@ request but has no recommendataions at present. 1. `into_variant` adapts a sender with multiple value completion signatures into a sender with just one value completion signature consisting of a `variant` of `tuple`s. -2. The name `into_variant` denotes a pipeable sender adaptor closure object. For a +2. The name `into_variant` denotes a pipeable sender adaptor object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If `Sndr` does not satisfy `sender`, `into_variant(sndr)` is ill-formed. @@ -9087,7 +9085,7 @@ request but has no recommendataions at present. sender that never completes with stopped, reporting cancellation by completing with an disengaged `optional`. -2. The name `stopped_as_optional` denotes a pipeable sender adaptor closure +2. The name `stopped_as_optional` denotes a pipeable sender adaptor object. For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. The expression `stopped_as_optional(sndr)` is expression-equivalent to: @@ -9124,7 +9122,7 @@ request but has no recommendataions at present. that never completes with stopped, reporting cancellation by completing with an error. -2. The name `stopped_as_error` denotes a pipeable sender adaptor closure object. +2. The name `stopped_as_error` denotes a pipeable sender adaptor object. For some subexpressions `sndr` and `err`, let `Sndr` be `decltype((sndr))` and let `Err` be `decltype((err))`. If the type `Sndr` does not satisfy `sender` or if the type `Err` doesn't satisfy `movable-value`, @@ -9498,7 +9496,7 @@ request but has no recommendataions at present. only if it is a function type with one of the following forms: * set_value_t(Vs...), where `Vs` - is an parameter pack of object or reference types. + is a pack of object or reference types. * set_error_t(Err), where `Err` is an object or reference type. * `set_stopped_t()` @@ -9511,11 +9509,11 @@ request but has no recommendataions at present. using gather-signatures = see below;
- 2. Let `Fns...` be a template parameter pack of the arguments of the + 2. Let `Fns` be a pack of the arguments of the `completion_signatures` specialization named by `Completions`, let - `TagFns` be a template parameter pack of the function + `TagFns` be a pack of the function types in `Fns` whose return types are `Tag`, and let - Tsn be a template parameter pack + Tsn be a pack of the function argument types in the `n`-th type in `TagFns`. Then, given two variadic templates `Tuple` and `Variant`, the type @@ -9525,7 +9523,7 @@ request but has no recommendataions at present. Ts0...), META-APPLY(Tuple, Ts1...), ... META-APPLY(Tuple, Tsm-1...))
, where `m` - is the size of the parameter pack `TagFns` and + is the size of the pack `TagFns` and META-APPLY(T, As...) is equivalent to:
@@ -9567,8 +9565,6 @@ request but has no recommendataions at present.
     
- - ### `execution::transform_completion_signatures` [exec.utils.tfxcmplsigs] ### {#spec-execution.snd_rec_utils.transform_completion_sigs} 1. `transform_completion_signatures` is an alias template used to transform one @@ -9596,7 +9592,7 @@ request but has no recommendataions at present.
-- end example] -3. This subclause makes use of the following exposition-only entities: +3. [exec.utils.tfxcmplsigs] makes use of the following exposition-only entities:
     template<class... As>
@@ -9622,8 +9618,8 @@ request but has no recommendataions at present.
     }
     
- 1. `SetValue` shall name an alias template such that for any template - parameter pack `As...`, the type `SetValue` is either ill-formed + 1. `SetValue` shall name an alias template such that for any + pack of types `As`, the type `SetValue` is either ill-formed or else valid-completion-signatures<SetValue<As...>> is satisfied. @@ -9642,7 +9638,7 @@ request but has no recommendataions at present. named by gather-signatures<set_error_t, InputSignatures, type_identity_t, error-list>, where `error-list` is an alias template such that - error-list<Ts...> names + error-list<Ts...> is type-list<SetError<Ts>...>. 5. Let `Ss` name the type `completion_signatures<>` if @@ -9654,38 +9650,36 @@ request but has no recommendataions at present. 6. If any of the above types are ill-formed, then `transform_completion_signatures` is ill-formed, + SetValue, SetError, SetStopped>` is ill-formed. 7. Otherwise, `transform_completion_signatures` names the type + AdditionalSignatures, SetValue, SetError, SetStopped>` is the type `completion_signatures` where `Sigs...` is the unique set of types in all the template arguments of all the `completion_signatures` - specializations in `[AdditionalSignatures, Vs..., Es..., Ss]`. + specializations in the set `AdditionalSignatures, Vs..., Es..., Ss`. ## Execution contexts [exec.ctx] ## {#spec-execution.contexts} -1. This subclause specifies some execution resources on which work can be - scheduled. - ### `run_loop` [exec.run.loop] ### {#spec-execution.contexts.run_loop} 1. A `run_loop` is an execution resource on which work can be scheduled. It - maintains a simple, thread-safe first-in-first-out queue of work. Its `run()` + maintains a thread-safe first-in-first-out queue of work. Its `run()` member function removes elements from the queue and executes them in a loop - on whatever thread of execution calls `run()`. + on the thread of execution calls `run()`. 2. A `run_loop` instance has an associated count that corresponds to the - number of work items that are in its queue. Additionally, a `run_loop` has an + number of work items that are in its queue. Additionally, a `run_loop` instance has an associated state that can be one of starting, running, or finishing. -3. Concurrent invocations of the member functions of `run_loop`, other than - `run` and its destructor, do not introduce data races. The member functions +3. Concurrent invocations of the member functions of `run_loop` other than + `run` and its destructor do not introduce data races. The member functions `pop_front`, `push_back`, and `finish` execute atomically. -4. Implementations are encouraged to use an intrusive +4. *Recommended practice:* Implementations are encouraged to use an intrusive queue of operation states to hold the work units to make scheduling - allocation-free. + allocation-free. +
     namespace std::execution {
@@ -9694,16 +9688,18 @@ request but has no recommendataions at present.
         class run-loop-scheduler; // exposition only
         class run-loop-sender; // exposition only
         struct run-loop-opstate-base { // exposition only
-          virtual void execute() = 0;
-          run_loop* loop;
-          run-loop-opstate-base* next;
+          virtual void execute() = 0;  // exposition only
+          run_loop* loop;  // exposition only
+          run-loop-opstate-base* next;  // exposition only
         };
         template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
           using run-loop-opstate = unspecified; // exposition only
 
+
+TODO: kebab these:
         // [exec.run.loop.members] Member functions:
-        run-loop-opstate-base* pop_front(); // exposition only
-        void push_back(run-loop-opstate-base*); // exposition only
+        run-loop-opstate-base* pop-front(); // exposition only
+        void push-back(run-loop-opstate-base*); // exposition only
 
       public:
         // [exec.run.loop.ctor] construct/copy/destroy
@@ -9726,7 +9722,7 @@ class run-loop-scheduler;
 
1. `run-loop-scheduler` is an unspecified type that models - the `scheduler` concept. + `scheduler`. 2. Instances of `run-loop-scheduler` remain valid until the end of the lifetime of the `run_loop` instance from which they were @@ -9737,17 +9733,21 @@ class run-loop-scheduler; 4. Let `sch` be an expression of type `run-loop-scheduler`. The expression - schedule(sch) is not potentially-throwing and has type - `run-loop-sender`. + schedule(sch) has type + `run-loop-sender` and is not potentially-throwing + if `sch` is not potentially-throwing.
 class run-loop-sender;
 
-1. `run-loop-sender` is an unspecified type such that - sender-of<run-loop-sender> is `true`. - Additionally, the types reported by its `error_types` associated type is - `exception_ptr`, and the value of its `sends_stopped` trait is `true`. +1. `run-loop-sender` is an unspecified type such that for any + type `Env`, completion_signatures_of_t<run-loop-sender, Env> + is: + +
+      completion_signatures<set_value_t(), set_error_t(exception_ptr), set_stopped_t()>
+      
2. An instance of `run-loop-sender` remains valid until the end of the lifetime of its associated `run_loop` instance. @@ -9776,7 +9776,7 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr> struct run-loop-opstate;
-1. run-loop-opstate<Rcvr> inherits unambiguously +1. run-loop-opstate<Rcvr> inherits privately and unambiguously from `run-loop-opstate-base`. 2. Let `o` be a non-`const` lvalue of type @@ -9791,8 +9791,8 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr> refers. * The type run-loop-opstate<Rcvr> overrides - run-loop-opstate-base::execute() such that - o.execute() is equivalent to the following: + run-loop-opstate-base::execute() such that + o.execute() is equivalent to the following:
         if (get_stop_token(REC(o)).stop_requested()) {
@@ -9807,7 +9807,7 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
 
         
         try {
-          o.loop->push_back(&o);
+          o.loop->push-back(&o);
         } catch(...) {
           set_error(std::move(REC(o)), current_exception());
         }
@@ -9832,27 +9832,27 @@ run_loop() noexcept;
 #### Member functions [exec.run.loop.members] #### {#spec-execution.contexts.run_loop.members}
 
 
-run-loop-opstate-base* pop_front();
+run-loop-opstate-base* pop-front();
 
1. Effects: Blocks ([defns.block]) until one of the following conditions is `true`: * count is `0` and state is finishing, in which case - `pop_front` returns `nullptr`; or + `pop-front` returns `nullptr`; or * count is greater than `0`, in which case an item is removed from the front of the queue, count is decremented by `1`, and the removed item is returned.
-void push_back(run-loop-opstate-base* item);
+void push-back(run-loop-opstate-base* item);
 
1. Effects: Adds `item` to the back of the queue and increments count by `1`. -2. Synchronization: This operation synchronizes with the `pop_front` +2. Synchronization: This operation synchronizes with the `pop-front` operation that obtains `item`.
@@ -9869,8 +9869,8 @@ void run();
 1. Effects: Equivalent to:
 
     
-    while (auto* op = pop_front()) {
-      op->execute();
+    while (auto* op = pop-front()) {
+      op->execute();
     }
     
@@ -9887,7 +9887,7 @@ void finish(); 1. Effects: Changes state to finishing. -2. Synchronization: This operation synchronizes with all `pop_front` +2. Synchronization: This operation synchronizes with all `pop-front` operations on this object. ## Coroutine utilities [exec.coro.utils] ## {#spec-execution.coro_utils} @@ -9952,7 +9952,7 @@ void finish(); Let `rcvr` be an rvalue expression of type `awaitable-receiver`, let `crcvr` be a `const` - lvalue that refers to `rcvr`, let `vs` be a parameter pack of types + lvalue that refers to `rcvr`, let `vs` be a pack of types `Vs...`, and let `err` be an arbitrary expression of type `Err`. Then: From 3902689dbad5522a08c7246c67ee9cec89ed9cd2 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 27 Jun 2024 10:34:44 -0700 Subject: [PATCH 79/89] bug fix to `receiver` and `scheduler` concepts, from @tcanens --- execution.bs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/execution.bs b/execution.bs index b403591..2c77308 100644 --- a/execution.bs +++ b/execution.bs @@ -6169,7 +6169,7 @@ namespace std::execution { namespace std::execution { template<class Sch> concept scheduler = - derived_from<typename Sch::scheduler_concept, scheduler_t> && + derived_from<typename remove_cvref_t<Sch>::scheduler_concept, scheduler_t> && queryable<Sch> && requires(Sch&& sch) { { schedule(std::forward<Sch>(sch)) } -> sender; @@ -6227,7 +6227,7 @@ namespace std::execution { namespace std::execution { template<class Rcvr> concept receiver = - derived_from<typename Rcvr::receiver_concept, receiver_t> && + derived_from<typename remove_cvref_t<Rcvr>::receiver_concept, receiver_t> && requires(const remove_cvref_t<Rcvr>& rcvr) { { get_env(rcvr) } -> queryable; } && From 362c95c9f8c5dc11319113fdf8056399a9f58653 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 27 Jun 2024 16:02:31 -0700 Subject: [PATCH 80/89] review feedback from the LWG afternoon session, 2024-06-27 --- execution.bs | 288 +++++++++++++++++++++++++++------------------------ 1 file changed, 154 insertions(+), 134 deletions(-) diff --git a/execution.bs b/execution.bs index 2c77308..f38ac5c 100644 --- a/execution.bs +++ b/execution.bs @@ -3996,6 +3996,13 @@ a new bullet as follows: [stopcallback.inplace.cons]) when a callback invocation exits via an exception. +* when a `run_loop` object is destroyed that is still in the `running` state + ([exec.run.loop]). + +* when `unhandled_stopped()` is called on a `with_awaitable_senders` object + ([exec.with.awaitable.senders]) whose continuation is not a handle to a + coroutine whose promise type has an `unhandled_stopped()` member function. +
@@ -5382,7 +5389,7 @@ template<class Initializer> 2. Let `q` be a query object, let `args` be a (possibly empty) pack of subexpressions, let `env` be a subexpression that refers to a queryable - object `o` of type `O`, and let `cenv` be a subexpression refering to `o` + object `o` of type `O`, and let `cenv` be a subexpression referring to `o` such that `decltype((cenv))` is `const O&`. The expression `q(env, args...)` is equal to ([concepts.equality]) the expression `q(cenv, args...)`. @@ -6479,7 +6486,7 @@ namespace std::execution { 1. Effects: Equivalent to: - - If sender-for<Sndr, transfer_t> is `true`, + - If sender-for<Sndr, continues_on_t> is `true`, then return Domain(); where `Domain` is the type of the following expression: @@ -6872,18 +6879,18 @@ namespace std::execution { communicate to users why. 15.
-        template<sender Sndr, queryable Env>
+        template<sender Sndr, queryable Env>
           constexpr auto write-env(Sndr&& sndr, Env&& env); // exposition only
         
1. `write-env` is an exposition-only sender adaptor that, when connected with a receiver `rcvr`, connects the adapted sender with a receiver whose execution environment is the result of joining the - `queryable` argument `env` to the result of `get_env(rcvr)`. + `queryable` argument `env` to the result of `get_env(rcvr)`. 2. Let `write-env-t` be an exposition-only empty class type. - 3. *Returns:* make-sender(make-env-t(), std::forward<Env>(env), std::forward<Sndr>(sndr)). + 3. *Returns:* make-sender(write-env-t(), std::forward<Env>(env), std::forward<Sndr>(sndr)). 4. *Remarks:* The exposition-only class template `impls-for` ([exec.snd.general]) is specialized for @@ -7700,12 +7707,12 @@ namespace std::execution { except that `sndr` is evaluated only once. 4. The exposition-only class template `impls-for` is specialized - for `transfer_t` as follows: + for `continues_on_t` as follows:
         namespace std::execution {
           template<>
-          struct impls-for<transfer_t> : default-impls {
+          struct impls-for<continues_on_t> : default-impls {
             static constexpr auto get_attrs =
               [](const auto& data, const auto& child) noexcept -> decltype(auto) {
                 return JOIN-ENV(SCHED-ATTRS(data), FWD-ENV(get_env(child)));
@@ -7715,7 +7722,7 @@ namespace std::execution {
         
5. Let `sndr` and `env` be subexpressions such that `Sndr` is `decltype((sndr))`. If - sender-for<Sndr, transfer_t> is `false`, then the expression + sender-for<Sndr, continues_on_t> is `false`, then the expression `continues_on.transform_sender(sndr, env)` is ill-formed; otherwise, it is equal to: @@ -7914,28 +7921,36 @@ namespace std::execution { `closure` with the async results of the sender, and that then transfers execution back to the execution resource on which `sndr` completed. -2. The name `on` denotes a customization point object. For some subexpressions +2. The name `on` denotes a pipeable sender adaptor object. For subexpressions `sch` and `sndr`, if `decltype((sch))` does not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, `on(sch, sndr)` is ill-formed. + If `sndr` is a pipeable sender adaptor closure object, `on(sch, sndr)` is + ambiguous with the partial application of the overload described below. 3. Otherwise, the expression `on(sch, sndr)` is expression-equivalent to:
     transform_sender(
       query-or-default(get_domain, sch, default_domain()),
-      make-sender(on, sch, sndr));
+      make-sender(on, sch, sndr))
     
-4. For a subexpression `closure`, if `decltype((closure))` is not a sender - adaptor closure object ([exec.adapt.objects]), the expression `on(sndr, sch, - closure)` is ill-formed; otherwise, it is expression-equivalent to: + except that `sch` is evaluated only once. + +4. For subexpressions `sndr`, `sch`, and `closure`, if `decltype((sch))` does + not satisfy `scheduler`, or `decltype((sndr))` does not satisfy `sender`, or + `closure` is not a pipeable sender adaptor closure object + ([exec.adapt.objects]), the expression `on(sndr, sch, closure)` is + ill-formed; otherwise, it is expression-equivalent to:
     transform_sender(
       get-domain-early(sndr),
-      make-sender(on, product-type{sch, closure}, sndr));
+      make-sender(on, product-type{sch, closure}, sndr))
     
+ except that `sndr` is evaluated only once. + 5. Let `out_sndr` and `env` be subexpressions, let `OutSndr` be `decltype((out_sndr))`, and let `Env` be `decltype((env))`. If sender-for<OutSndr, on_t> is `false`, then the @@ -7955,25 +7970,25 @@ namespace std::execution { }; - ... where the member function `get_completion_signatures` returns an + where the member function `get_completion_signatures` returns an object of a type that is not a specialization of the `completion_signatures` class template. - 2. `on.transform_env(out_sndr, env)` is equivalent to: + 2. The expression `on.transform_env(out_sndr, env)` has effects equivalent to:
-        auto& [_, data, _] = out_sndr;
+        auto&& [_, data, _] = out_sndr;
         if constexpr (scheduler<decltype(data)>) {
-          return JOIN-ENV(SCHED-ENV(data), FWD-ENV(std::forward<Env>(env)));
+          return JOIN-ENV(SCHED-ENV(std::forward_like<OutSndr>(data)), FWD-ENV(std::forward<Env>(env)));
         } else {
           return std::forward<Env>(env);
         }
         
- 3. `on.transform_sender(out_sndr, env)` is equivalent to: + 3. The expression `on.transform_sender(out_sndr, env)` has effects equivalent to:
-        auto& [_, data, child] = out_sndr;
+        auto&& [_, data, child] = out_sndr;
         if constexpr (scheduler<decltype(data)>) {
           auto orig_sch =
             query-with-default(get_scheduler, env, not-a-scheduler());
@@ -8012,57 +8027,57 @@ namespace std::execution {
         inform users that their usage of `on` is incorrect because there is no
         available scheduler onto which to restore execution.
 
-LEWG is uncomfortable with specifying the semantic
-requirements of `on` customizations in terms of "semantic equivalence" to the
-lowered expressions. LEWG would like to clarify what effects are considered
-salient when determining semantic equivalence. The author thinks this is a fair
-request but has no recommendataions at present.
-
-6. Let the subexpression `out_sndr` denote the result of the invocation `on(sch,
-    sndr)` or an object equal to such, let `OutSndr` be `decltype((out_sndr))`,
-    let the subexpression `rcvr` denote a receiver such that
-    `sender_to` is `true`, and let
-    `sch_copy` and `sndr_copy` be lvalue subexpressions refering to objects
-    decay-copied from `sch` and `sndr` respectively.
+6. Let `out_sndr` be a subexpression denoting a sender returned from
+    `on(sch, sndr)` or one equal to such, and let `OutSndr` be the type
+    `decltype((out_sndr))`. Let `out_rcvr` be a subexpression denoting a
+    receiver that has an environment of type `Env` such that `sender_in` is `true`. Let `op` be an lvalue referring to the operation state that
+    results from connecting `out_sndr` with `out_rcvr`. Calling `start(op)`
+    shall:
+  
+    1. Remember the current scheduler, `get_scheduler(get_env(rcvr))`.
+  
+    2. Start `sndr` on an execution agent belonging to `sch`'s associated
+        execution resource.
+
+    4. Upon `sndr`'s completion, transfer execution back to the execution
+        resource associated with the scheduler remembered in step 1.
+
+    5. Forward `sndr`'s async result to `out_rcvr`.
+
+    If any scheduling operation fails, an error completion on `out_rcvr` shall
+    be executed on an unspecified execution agent.
+
+7. Let `out_sndr` be a subexpression denoting a sender returned from
+    `on(sndr, sch, closure)` or one equal to such, and let `OutSndr` be the type
+    `decltype((out_sndr))`. Let `out_rcvr` be a subexpression denoting a
+    receiver that has an environment of type `Env` such that `sender_in` is `true`. Let `op` be an lvalue referring to the operation state that
+    results from connecting `out_sndr` with `out_rcvr`. Calling `start(op)`
+    shall:
     
-    The expression `connect(out_sndr, rcvr)` has undefined behavior unless it
-    creates an asynchronous operation as if by calling `connect(S, rcvr)`, where
-    `S` is a sender expression semantically equivalent to:
+    1. Remember the current scheduler, which is the first of the following
+        expressions that is well-formed:
 
-    
-    continues_on(
-      starts_on(std::forward_like<OutSndr>(sch_copy), std::forward_like<OutSndr>(sndr_copy)),
-      orig_sch)
-    
+ - `get_completion_scheduler(get_env(sndr))` - where `orig_sch` is `get_scheduler(get_env(rcvr))`. + - `get_scheduler(get_env(rcvr))` + + 2. Start `sndr` on the current execution agent. -7. Let the subexpression `out_sndr2` denote the result of the invocation - `on(sndr, sch, closure)` or an object copied or moved from such, let - `OutSndr2` be `decltype((out_sndr2))`, let the subexpression `rcvr2` denote - a receiver such that `sender_to` - is `true`, and let `sndr_copy`, `sch_copy`, and `closure_copy` be lvalue - subexpressions refering to objects decay-copied from `sndr`, `sch`, and - `closure` respectively. + 3. Upon `sndr`'s completion, transfer execution to an agent owned by `sch`'s + associated execution resource. + + 4. Forward `sndr`'s async result as if by connecting and starting a + sender `closure(S)`, where `S` is a sender that completes + synchronously with `sndr`'s async result. - The expression `connect(out_sndr2, rcvr2)` has undefined behavior unless it - creates an asynchronous operation as if by calling `connect(S2, rcvr2)`, where - `S2` is a sender expression semantically equivalent to: - -
-    write-env(
-      continues_on(
-        std::forward_like<OutSndr2>(closure_copy)(
-          continues_on(
-            write-env(std::forward_like<OutSndr2>(sndr_copy), SCHED-ENV(orig_sch)),
-            sch_copy)),
-        orig_sch),
-      SCHED-ENV(sch_copy))
-    
+ 5. Upon completion of the operation started in step 4, transfer execution + back to the execution resource associated with the scheduler remembered + in step 1 and forward the operation's async result to `out_rcvr`. - where `orig_sch` is an lvalue refering to an object decay-copied from - `get_completion_scheduler(get_env(sndr_copy))` if that - expression is well-formed; otherwise, `get_scheduler(get_env(rcvr2))`. + If any scheduling operation fails, an error completion on `out_rcvr` shall + be executed on an unspecified execution agent. #### `execution::then`, `execution::upon_error`, `execution::upon_stopped` [exec.then] #### {#spec-execution.senders.adaptor.then} @@ -9665,7 +9680,7 @@ request but has no recommendataions at present. 1. A `run_loop` is an execution resource on which work can be scheduled. It maintains a thread-safe first-in-first-out queue of work. Its `run()` member function removes elements from the queue and executes them in a loop - on the thread of execution calls `run()`. + on the thread of execution that calls `run()`. 2. A `run_loop` instance has an associated count that corresponds to the number of work items that are in its queue. Additionally, a `run_loop` instance has an @@ -9692,11 +9707,9 @@ request but has no recommendataions at present. run_loop* loop; // exposition only run-loop-opstate-base* next; // exposition only }; - template<receiver_of<completion_signatures<set_value_t()>> Rcvr> + template<class Rcvr> using run-loop-opstate = unspecified; // exposition only - -TODO: kebab these: // [exec.run.loop.members] Member functions: run-loop-opstate-base* pop-front(); // exposition only void push-back(run-loop-opstate-base*); // exposition only @@ -9741,9 +9754,9 @@ class run-loop-scheduler; class run-loop-sender;
-1. `run-loop-sender` is an unspecified type such that for any - type `Env`, completion_signatures_of_t<run-loop-sender, Env> - is: +1. `run-loop-sender` is an exposition-only type that satisfies `sender`. + For any type `Env`, + completion_signatures_of_t<run-loop-sender, Env> is:
       completion_signatures<set_value_t(), set_error_t(exception_ptr), set_stopped_t()>
@@ -9754,25 +9767,25 @@ class run-loop-sender;
 
 3. Let `sndr` be an expression of type
     `run-loop-sender`, let `rcvr` be an
-    expression such that decltype(rcvr) models the
-    `receiver_of` concept, and let `C` be either `set_value_t` or
-    `set_stopped_t`. Then:
+    expression such that receiver_of<decltype((rcvr)), CS>
+    is `true` where `CS` is the `completion_signatures` specialization above. Let
+    `C` be either `set_value_t` or `set_stopped_t`. Then:
 
     * The expression connect(sndr, rcvr) has type
-        run-loop-opstate<decay_t<decltype(rcvr)>>
-        and is potentially-throwing if and only if the initialiation of
-        decay_t<decltype(rcvr)> from
-        `rcvr` is potentially-throwing.
+        run-loop-opstate<decay_t<decltype((rcvr))>>
+        and is potentially-throwing if and only if (void(sndr),
+        auto(rcvr)) is potentially-throwing.
 
     * The expression
         get_completion_scheduler<C>(get_env(sndr)) is
-        not potentially-throwing, has type
+        potentially-throwing if and only if `sndr` is 
+        potentially-throwing, has type
         `run-loop-scheduler`, and compares equal to the
         `run-loop-scheduler` instance from which
         `sndr` was obtained.
 
 
-template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
+template<class Rcvr>
   struct run-loop-opstate;
 
@@ -9792,7 +9805,7 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr> * The type run-loop-opstate<Rcvr> overrides run-loop-opstate-base::execute() such that - o.execute() is equivalent to the following: + o.execute() is equivalent to:
         if (get_stop_token(REC(o)).stop_requested()) {
@@ -9802,12 +9815,11 @@ template<receiver_of<completion_signatures<set_value_t()>> Rcvr>
         }
         
- * The expression start(o) is equivalent to the - following: + * The expression start(o) is equivalent to:
         try {
-          o.loop->push-back(&o);
+          o.loop->push-back(addressof(o));
         } catch(...) {
           set_error(std::move(REC(o)), current_exception());
         }
@@ -9856,17 +9868,20 @@ void push-back(run-loop-opstate-base* item);
     operation that obtains `item`.
 
 
-run-loop-scheduler run_loop::get_scheduler();
+run-loop-scheduler get_scheduler();
 
-1. Returns: an instance of `run-loop-scheduler` that +1. Returns: An instance of `run-loop-scheduler` that can be used to schedule work onto this `run_loop` instance.
 void run();
 
-1. Effects: Equivalent to: +1. Precondition: state is starting. + +2. Effects: Sets the state to running. Then, + equivalent to:
     while (auto* op = pop-front()) {
@@ -9874,12 +9889,8 @@ void run();
     }
     
-2. Precondition: state is starting. - -3. Postcondition: state is finishing. - -4. Remarks: While the loop is executing, state is running. - When state changes, it does so without introducing data races. +3. Remarks: When state changes, it does so without introducing + data races.
 void finish();
@@ -9887,22 +9898,22 @@ void finish();
 
 1. Effects: Changes state to finishing.
 
-2. Synchronization: This operation synchronizes with all `pop-front`
-    operations on this object.
+2. Synchronization: `finish` synchronizes with the `pop-front`
+    operation that returns `nullptr`.
 
 ## Coroutine utilities [exec.coro.utils] ## {#spec-execution.coro_utils}
 
 ### `execution::as_awaitable` [exec.as.awaitable] ### {#spec-execution.coro_utils.as_awaitable}
 
 1. `as_awaitable` transforms an object into one that is awaitable within a
-    particular coroutine. This subclause makes use of the following
+    particular coroutine. [exec.coro.utils] makes use of the following
     exposition-only entities:
 
     
     namespace std::execution {
       template<class Sndr, class Promise>
         concept awaitable-sender =
-          single-sender<Sndr, env_of_t> &&
+          single-sender<Sndr, env_of_t<Promise>> &&
           sender_to<Sndr, awaitable-receiver> && // see below
           requires (Promise& p) {
             { p.unhandled_stopped() } -> convertible_to<coroutine_handle<>>;
@@ -9914,7 +9925,7 @@ void finish();
     
2. The type sender-awaitable<Sndr, Promise> is - equivalent to the following: + equivalent to:
         namespace std::execution {
@@ -9939,7 +9950,7 @@ void finish();
         }
         
- 1. `awaitable-receiver` is equivalent to the following: + 1. `awaitable-receiver` is equivalent to:
             struct awaitable-receiver {
@@ -9952,19 +9963,19 @@ void finish();
 
             Let `rcvr` be an rvalue expression of type
             `awaitable-receiver`, let `crcvr` be a `const`
-            lvalue that refers to `rcvr`, let `vs` be a pack of types
-            `Vs...`, and let `err` be an arbitrary expression of type `Err`.
+            lvalue that refers to `rcvr`, let `vs` be a pack of subexpressions,
+            and let `err` be an expression of type `Err`.
             Then:
 
-            1. If constructible_from<result-type, Vs...>
+            1. If constructible_from<result-type, decltype((vs))...>
                 is satisfied, the expression `set_value(rcvr, vs...)` is
                 equivalent to:
 
                 
                 try {
-                  rcvr.result-ptr->emplace<1>(vs...);
+                  rcvr.result-ptr->template emplace<1>(vs...);
                 } catch(...) {
-                  rcvr.result-ptr->emplace<2>(current_exception());
+                  rcvr.result-ptr->template emplace<2>(current_exception());
                 }
                 rcvr.continuation.resume();
                 
@@ -9974,30 +9985,33 @@ void finish(); 2. The expression `set_error(rcvr, err)` is equivalent to:
-                rcvr.result-ptr->emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
+                rcvr.result-ptr->template emplace<2>(AS-EXCEPT-PTR(err)); // see [exec.general]
                 rcvr.continuation.resume();
                 
- 3. The expression `set_stopped(rcvr)` is equivalent to - static_cast<coroutine_handle<>>(rcvr.continuation.promise().unhandled_stopped()).resume(). + 3. The expression `set_stopped(rcvr)` is equivalent to: + +
+                static_cast<coroutine_handle<>>(rcvr.continuation.promise().unhandled_stopped()).resume();
+                
4. For any expression `tag` whose type satisfies `forwarding-query` and for any pack of subexpressions `as`, `get_env(crcvr).query(tag, as...)` is expression-equivalent to tag(get_env(as_const(crcvr.continuation.promise())), - as...) when that expression is well-formed. + as...). - 2. sender-awaitable(Sndr&& sndr, Promise& p) + 2. sender-awaitable(Sndr&& sndr, Promise& p); - - Effects: initializes `state` with + 1. Effects: Initializes `state` with connect(std::forward<Sndr>(sndr), - awaitable-receiver{&result, + awaitable-receiver{addressof(result), coroutine_handle<Promise>::from_promise(p)}). - 3. value-type await_resume() + 3. value-type await_resume(); - - Effects: equivalent to: + 1. Effects: Equivalent to:
                 if (result.index() == 2)
@@ -10006,21 +10020,19 @@ void finish();
                   return std::forward<value-type>(get<1>(result));
                 
-2. `as_awaitable` is a customization point object. For some subexpressions +2. `as_awaitable` is a customization point object. For subexpressions `expr` and `p` where `p` is an lvalue, `Expr` names the type - `decltype((expr))` and `Promise` names the type `decltype((p))`, - `as_awaitable(expr, p)` is expression-equivalent to the following: + `decltype((expr))` and `Promise` names the type `decay_t`, + `as_awaitable(expr, p)` is expression-equivalent to: 1. `expr.as_awaitable(p)` if that expression is well-formed. * Mandates: is-awaitable<A, Promise> is `true`, where `A` is the type of the expression above. - 2. Otherwise, `expr` if is-awaitable<Expr, U> + 2. Otherwise, `void(p), expr` if is-awaitable<Expr, U> is `true`, where `U` is an unspecified class type that - lacks a member named `await_transform`. The - condition is not is-awaitable<Expr, Promise> as - that creates the potential for constraint recursion. + is not `Promise` and that lacks a member named `await_transform`. * Preconditions: is-awaitable<Expr, Promise> is `true` and the expression `co_await expr` in a @@ -10031,7 +10043,9 @@ void finish(); 3. Otherwise, sender-awaitable{expr, p} if awaitable-sender<Expr, Promise> is `true`. - 4. Otherwise, `expr`. + 4. Otherwise, `void(p), expr`. + + except that the evaluations of `expr` and `p` are indeterminately sequenced. ### `execution::with_awaitable_senders` [exec.with.awaitable.senders] ### {#spec-execution.coro_utils.with_awaitable_senders} @@ -10041,14 +10055,14 @@ void finish(); In addition, it provides a default implementation of `unhandled_stopped()` such that if a sender completes by calling `set_stopped`, it is treated as if an uncatchable "stopped" exception were thrown from the - await-expression. In practice, the coroutine is never resumed, and - the `unhandled_stopped` of the coroutine caller's promise type is called. + await-expression. The coroutine is never resumed, and + the `unhandled_stopped` of the coroutine caller's promise type is called.
     namespace std::execution {
       template<class-type Promise>
         struct with_awaitable_senders {
-          template<OtherPromise>
+          template<class OtherPromise>
             requires (!same_as<OtherPromise, void>)
           void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
 
@@ -10061,21 +10075,25 @@ void finish();
           template<class Value>
           see below await_transform(Value&& value);
 
-          private:
+        private:
           // exposition only
-          [[noreturn]] static coroutine_handle<> default_unhandled_stopped(void*) noexcept {
+          [[noreturn]] static coroutine_handle<> default-unhandled-stopped(void*) noexcept {
             terminate();
           }
           coroutine_handle<> continuation{}; // exposition only
           // exposition only
-          coroutine_handle<> (*stopped-handler)(void*) noexcept = &default_unhandled_stopped;
+          coroutine_handle<> (*stopped-handler)(void*) noexcept = &default-unhandled-stopped;
         };
     }
     
-2. `void set_continuation(coroutine_handle h) noexcept` +2.
+    template<class OtherPromise>
+      requires (!same_as<OtherPromise, void>)
+    void set_continuation(coroutine_handle h) noexcept;
+    
- - Effects: equivalent to: + 1. Effects: Equivalent to:
       continuation = h;
@@ -10085,14 +10103,16 @@ void finish();
             .promise().unhandled_stopped();
         };
       } else {
-        stopped-handler = default_unhandled_stopped;
+        stopped-handler = &default-unhandled-stopped;
       }
       
-3. template<class Value>
- call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value)
+3.
+    template<class Value>
+    call-result-t<as_awaitable_t, Value, Promise&> await_transform(Value&& value);
+    
- - Effects: equivalent to: + 1. Effects: Equivalent to:
       return as_awaitable(std::forward<Value>(value), static_cast<Promise&>(*this));

From 7144de42d53b48b50c40db87a834cce416487053 Mon Sep 17 00:00:00 2001
From: Lewis Baker 
Date: Thu, 27 Jun 2024 19:48:59 -0500
Subject: [PATCH 81/89] Apply changes from P3187R1 (#254)

* Remove `ensure_started` algorithm

Applying changes from paper P3187.

Changes were more complicated due to the merging of split() and
ensure_started() wording. This wording has now been simplified to
now only describe the split() algorithm.

* Remove start_detached() and execute() functions.

Applies changes from P3187R1.

Note that this change also removes the `execute_may_block_caller`
query as this was only relevant to the `execute()` function which
is also removed here.

* bug fixes

* Update execution.bs

* remove other mentions of `ensure_started`, `start_detached` and `execute`

* fix bug in `split`'s `start` operation that lewis spotted

---------

Co-authored-by: Lewis Baker 
Co-authored-by: Eric Niebler 
---
 execution.bs | 352 +++++++++------------------------------------------
 1 file changed, 59 insertions(+), 293 deletions(-)

diff --git a/execution.bs b/execution.bs
index f38ac5c..f7de51e 100644
--- a/execution.bs
+++ b/execution.bs
@@ -1503,6 +1503,9 @@ The changes since R9 are as follows:
 
 Fixes:
 
+  * `ensure_started`, `start_detached`, `execute`, and `execute_may_block_caller`
+    are removed from the proposal. They are to be replaced with safer and more
+    structured APIs by [@P3149R3].
 
 Enhancements:
 
@@ -2303,7 +2306,7 @@ usages will only accept multi-shot senders.
 Algorithms that accept senders will typically either decay-copy an input sender
 and store it somewhere for later usage (for example as a data-member of the
 returned sender) or will immediately call `execution::connect` on the input
-sender, such as in `this_thread::sync_wait` or `execution::start_detached`.
+sender, such as in `this_thread::sync_wait`.
 
 Some multi-use sender algorithms may require that an input sender be
 copy-constructible but will only call `execution::connect` on an rvalue of each
@@ -2573,10 +2576,10 @@ accelerator can sometimes be considerable.
 However, in the process of working on this paper and implementations of the
 features proposed within, our set of requirements has shifted, as we understood
 the different implementation strategies that are available for the feature set
-of this paper better, and, after weighting the earlier concerns against the
+of this paper better, and, after weighing the earlier concerns against the
 points presented below, we have arrived at the conclusion that a purely lazy
 model is enough for most algorithms, and users who intend to launch work earlier
-may use an algorithm such as `ensure_started` to achieve that goal. We have also
+may write an algorithm to achieve that goal. We have also
 come to deeply appreciate the fact that a purely lazy model allows both the
 implementation and the compiler to have a much better understanding of what the
 complete graph of tasks looks like, allowing them to better optimize the code -
@@ -3239,8 +3242,7 @@ is related to the sender arguments it has received.
 Sender adaptors are lazy, that is, they are never allowed to submit any
 work for execution prior to the returned sender being [=started=] later on, and
 are also guaranteed to not start any input senders passed into them. Sender
-consumers such as [[#design-sender-consumer-start_detached]] and
-[[#design-sender-consumer-sync_wait]] start senders.
+consumers such as [[#design-sender-consumer-sync_wait]] start senders.
 
 For more implementer-centric description of starting senders, see
 [[#design-laziness]].
@@ -3483,50 +3485,11 @@ execution::sender auto final = execution::then(both, [](auto... args){
 // when final executes, it will print "the two args: 1, abc"
 
-### `execution::ensure_started` ### {#design-sender-adaptor-ensure_started} - -
-execution::sender auto ensure_started(
-    execution::sender auto sender
-);
-
- -Once `ensure_started` returns, it is known that the provided sender has been -[=connect|connected=] and `start` has been called on the resulting operation -state (see [[#design-states]]); in other words, the work described by the -provided sender has been submitted -for execution on the appropriate execution resources. Returns a sender which -completes when the provided sender completes and sends values equivalent to -those of the provided sender. - -If the returned sender is destroyed before `execution::connect()` is called, or -if `execution::connect()` is called but the returned operation-state is -destroyed before `execution::start()` is called, then a stop-request is sent to -the eagerly launched operation and the operation is detached and will run to -completion in the background. Its result will be discarded when it eventually -completes. - -Note that the application will need to make sure that resources are kept alive -in the case that the operation detaches. e.g. by holding a `std::shared_ptr` to -those resources or otherwise having some out-of-band way to signal completion of -the operation so that resource release can be sequenced after the completion. - ## User-facing sender consumers ## {#design-sender-consumers} A [=sender consumer=] is an algorithm that takes one or more senders, which it may `execution::connect`, as parameters, and does not return a sender. -### `execution::start_detached` ### {#design-sender-consumer-start_detached} - -
-void start_detached(
-    execution::sender auto sender
-);
-
- -Like `ensure_started`, but does not return a value; if the provided sender sends -an error instead of a value, `std::terminate` is called. - ### `this_thread::sync_wait` ### {#design-sender-consumer-sync_wait}
@@ -3537,12 +3500,12 @@ auto sync_wait(
 
`this_thread::sync_wait` is a sender consumer that submits the work described by -the provided sender for execution, similarly to `ensure_started`, except that it -blocks the current `std::thread` or thread of `main` until the work is +the provided sender for execution, +blocking the current `std::thread` or thread of `main` until the work is completed, and returns an optional tuple of values that were sent by the provided sender on its completion of work. Where [[#design-sender-factory-schedule]] and [[#design-sender-factory-just]] are -meant to enter the domain of senders, `sync_wait` is meant to exit +meant to enter the domain of senders, `sync_wait` is one way to exit the domain of senders, retrieving the result of the task graph. If the provided sender sends an error instead of values, `sync_wait` throws that @@ -3568,28 +3531,6 @@ different synchronization mechanisms than `std::thread`'s will provide their own flavors of `sync_wait` as well (assuming their execution agents have the means to block in a non-deadlock manner). -## `execution::execute` ## {#design-execute} - -In addition to the three categories of functions presented above, we also -propose to include a convenience function for fire-and-forget eager one-way -submission of an invocable to a scheduler, to fulfil the role of one-way -executors from P0443. - -
-void execution::execute(
-    execution::schedule auto sched,
-    std::invocable auto fn
-);
-
- -Submits the provided function for execution on the provided scheduler, as-if by: - -
-auto snd = execution::schedule(sched);
-auto work = execution::then(snd, fn);
-execution::start_detached(work);
-
- # Design - implementer side # {#design-implementer} ## Receivers serve as glue between senders ## {#design-receivers} @@ -3632,8 +3573,8 @@ algorithm: `start`, which serves as the submission point of the work represented by a given operation state. Operation states are not a part of the user-facing API of this proposal; they -are necessary for implementing sender consumers like `execution::ensure_started` -and `this_thread::sync_wait`, and the knowledge of them is necessary to +are necessary for implementing sender consumers like `this_thread::sync_wait`, +and the knowledge of them is necessary to implement senders, so the only users who will interact with operation states directly are authors of senders and authors of sender algorithms. @@ -3765,9 +3706,7 @@ that accepts a sender as its first argument, should do the following: ## Sender adaptors are lazy ## {#design-laziness} Contrary to early revisions of this paper, we propose to make all sender -adaptors perform strictly lazy submission, unless specified otherwise (the one -notable exception in this paper is [[#design-sender-adaptor-ensure_started]], -whose sole purpose is to start an input sender). +adaptors perform strictly lazy submission, unless specified otherwise. Strictly lazy submission means that there is a guarantee that no work is submitted to an execution resource before a receiver is @@ -3794,10 +3733,7 @@ capable of removing the senders abstraction entirely, while still allowing for composition of functions across different parts of a program. The second way for this to occur is when a sender algorithm is specialized for a -specific set of arguments. For instance, we expect that, for senders which are -known to have been started already, [[#design-sender-adaptor-ensure_started]] -will be an identity transformation, because the sender algorithm will be -specialized for such senders. Similarly, an implementation could recognize two +specific set of arguments. For instance, an implementation could recognize two subsequent [[#design-sender-adaptor-bulk]]s of compatible shapes, and merge them together into a single submission of a GPU kernel. @@ -5291,7 +5227,6 @@ template<class Initializer> [exec.recv]Receivers [exec.opstate]Operation states [exec.snd]Senders -[exec.execute]One-way execution 3. Table 2 shows the types of customization point objects @@ -5307,7 +5242,7 @@ template<class Initializer> core provide core execution functionality, and connection between core components - e.g., `connect`, `start`, `execute` + e.g., `connect`, `start` completion functions @@ -5321,7 +5256,7 @@ template<class Initializer>
  • sender factories (e.g., `schedule`, `just`, `read_env`)
  • sender adaptors (e.g., `continues_on`, `then`, `let_value`)
  • -
  • sender consumers (e.g., `start_detached`, `sync_wait`)
  • +
  • sender consumers (e.g., `sync_wait`)
@@ -5332,7 +5267,7 @@ template<class Initializer>
  • general queries (e.g., `get_allocator`, `get_stop_token`)
  • environment queries (e.g., `get_scheduler`, `get_delegation_scheduler`)
  • -
  • scheduler queries (e.g., `get_forward_progress_guarantee`, `execute_may_block_caller`)
  • +
  • scheduler queries (e.g., `get_forward_progress_guarantee`)
  • sender attribute queries (e.g., `get_completion_scheduler`)
@@ -5815,7 +5750,6 @@ namespace std::execution { struct let_stopped_t { see below }; struct bulk_t { see below }; struct split_t { see below }; - struct ensure_started_t { see below }; struct when_all_t { see below }; struct when_all_with_variant_t { see below }; struct into_variant_t { see below }; @@ -5834,17 +5768,12 @@ namespace std::execution { inline constexpr let_stopped_t let_stopped{}; inline constexpr bulk_t bulk{}; inline constexpr split_t split{}; - inline constexpr ensure_started_t ensure_started{}; inline constexpr when_all_t when_all{}; inline constexpr when_all_with_variant_t when_all_with_variant{}; inline constexpr into_variant_t into_variant{}; inline constexpr stopped_as_optional_t stopped_as_optional{}; inline constexpr stopped_as_error_t stopped_as_error{}; - // [exec.consumers], sender consumers - struct start_detached_t { see below }; - inline constexpr start_detached_t start_detached{}; - // [exec.utils], sender and receiver utilities // [exec.utils.cmplsigs] template<class Fn> @@ -5885,10 +5814,7 @@ namespace std::execution { } namespace std::this_thread { - // [exec.queries], queries - struct execute_may_block_caller_t { see below }; - inline constexpr execute_may_block_caller_t execute_may_block_caller{}; - + // [exec.consumers], consumers struct sync_wait_t { see below }; struct sync_wait_with_variant_t { see below }; @@ -5897,10 +5823,6 @@ namespace std::this_thread { } namespace std::execution { - // [exec.execute], one-way execution - struct execute_t { see below }; - inline constexpr execute_t execute{}; - // [exec.as.awaitable] struct as_awaitable_t { see below }; inline constexpr as_awaitable_t as_awaitable{}; @@ -6111,29 +6033,6 @@ namespace std::execution { `forward_progress_guarantee::parallel`, all such execution agents shall provide at least the parallel forward progress guarantee. -### `this_thread::execute_may_block_caller` [exec.execute.may.block.caller] ### {#spec-execution.execute_may_block_caller} - -1. `execute_may_block_caller` asks a scheduler `sch` whether any invocation of - the `execute` algorithm ([exec.execute]) with `sch` may block the current - thread of execution ([defns.block]). - -2. The name `execute_may_block_caller` denotes a query object. For - a subexpression `sch`, let `Sch` be `decltype((sch))`. If `Sch` does not - satisfy `scheduler`, `execute_may_block_caller(sch)` is ill-formed. - Otherwise, `execute_may_block_caller(sch)` is - expression-equivalent to: - - 1. MANDATE-NOTHROW(as_const(sch).query(execute_may_block_caller)), - if that expression is well-formed. - - * Mandates: The type of the expression above is `bool`. - - 2. Otherwise, `true`. - -3. If `execute_may_block_caller(sch)` returns `false` for some scheduler `sch`, - no invocation of the `execute` algorithm with `sch` shall block the calling - thread. - ### `execution::get_completion_scheduler` [exec.completion.scheduler] ### {#spec-execution.get_completion_scheduler} 1. get_completion_scheduler<completion-tag> obtains the @@ -8388,37 +8287,34 @@ namespace std::execution { - propagates all completion operations sent by `sndr`. -#### `execution::split` and `execution::ensure_started` [exec.split] #### {#spec-execution.senders.adapt.split} +#### `execution::split` [exec.split] #### {#spec-execution.senders.adapt.split} 1. `split` adapts an arbitrary sender into a sender that can be connected - multiple times. `ensure_started` eagerly starts the execution of a sender, - returning a sender that is usable as input to additional sender algorithms. + multiple times. -2. Let `shared-env` be the type of an environment such that, +2. Let `split-env` be the type of an environment such that, given an instance `env`, the expression `get_stop_token(env)` is well-formed and has type `inplace_stop_token`. -3. The names `split` and `ensure_started` denote pipeable sender adaptor objects. - Let the expression `shared-cpo` be one of `split` or - `ensure_started`. For a subexpression `sndr`, let `Sndr` be - `decltype((sndr))`. If sender_in<Sndr, shared-env> is - `false`, shared-cpo(sndr) is ill-formed. +3. The name `split` denotes a pipeable sender adaptor object. + For a subexpression `sndr`, let `Sndr` be `decltype((sndr))`. + If sender_in<Sndr, split-env> is + `false`, split(sndr) is ill-formed. -4. Otherwise, the expression shared-cpo(sndr) is +4. Otherwise, the expression split(sndr) is expression-equivalent to:
       transform_sender(
         get-domain-early(sndr),
-        make-sender(shared-cpo, {}, sndr))
+        make-sender(split, {}, sndr))
       
except that `sndr` is evaluated only once. - The default implementation of `transform_sender` - will have the effect of connecting the sender to a receiver and, in the - case of `ensure_started`, calling `start` on the resulting operation - state. It will return a sender with a different tag type. + will have the effect of connecting the sender to a receiver. + It will return a sender with a different tag type. 5. Let `local-state` denote the following exposition-only class template: @@ -8427,7 +8323,6 @@ namespace std::execution { struct local-state-base { // exposition only virtual ~local-state-base() = default; virtual void notify() noexcept = 0; // exposition only - virtual void detach() noexcept = 0; // exposition only }; template<class Sndr, class Rcvr> @@ -8439,7 +8334,6 @@ namespace std::execution { ~local-state(); void notify() noexcept override; - void detach() noexcept override; private: optional<on-stop-callback> on_stop; // exposition only @@ -8467,7 +8361,6 @@ namespace std::execution { 1. *Effects:* Equivalent to:
-            detach();
             sh_state->dec-ref();
             
@@ -8479,42 +8372,29 @@ namespace std::execution {
             on_stop.reset();
             visit(
-              [this]<class Tuple>(Tuple&& tupl) noexcept -> void {
+              [this](const auto& tupl) noexcept -> void {
                 apply(
-                  [this](auto tag, auto&... args) noexcept -> void {
-                    tag(std::move(*rcvr), std::forward_like<Tuple>(args)...);
+                  [this](auto tag, const auto&... args) noexcept -> void {
+                    tag(std::move(*rcvr), args...);
                   },
                   tupl);
               },
-              QUAL(sh_state->result));
+              sh_state->result);
             
- where `QUAL` is `std::move` if - same_as<tag_of_t<Sndr>, - ensure-started-impl-tag> is `true`, and `as_const` - otherwise. - - 4.
-        void detach() noexcept override;
- - 1. *Effects:* Equivalent to sh_state->detach() if - same_as<tag_of_t<Sndr>, - ensure-started-impl-tag> is `true`; otherwise, - nothing. - -6. Let `shared-receiver` denote the following exposition-only class +6. Let `split-receiver` denote the following exposition-only class template:
     namespace std::execution {
       template<class Sndr>
-      struct shared-receiver {
+      struct split-receiver {
         using receiver_concept = receiver_t;
 
         template<class Tag, class... Args>
         void complete(Tag, Args&&... args) noexcept { // exposition only
+          using tuple_t = decayed-tuple<Tag, Args...>;
           try {
-            using tuple_t = decayed-tuple<Tag, Args...>;
             sh_state->result.template emplace<tuple_t>(Tag(), std::forward<Args>(args)...);
           } catch (...) {
             using tuple_t = tuple<set_error_t, exception_ptr>;
@@ -8568,7 +8448,6 @@ namespace std::execution {
 
         void start-op() noexcept;  // exposition only
         void notify() noexcept;  // exposition only
-        void detach() noexcept;  // exposition only
         void inc-ref() noexcept; // exposition only
         void dec-ref() noexcept; // exposition only
 
@@ -8577,7 +8456,7 @@ namespace std::execution {
         state-list-type waiting_states;    // exposition only
         atomic<bool> completed{false};   // exposition only
         atomic<size_t> ref_count{1};   // exposition only
-        connect_result_t<Sndr, shared-receiver<Sndr>> op_state;    // exposition only
+        connect_result_t<Sndr, split-receiver<Sndr>> op_state;    // exposition only
       };
     }
     
@@ -8600,7 +8479,7 @@ namespace std::execution { explicit shared-state(Sndr&& sndr);
1. *Effects:* Initializes `op_state` with the result of - connect(std::forward<Sndr>(sndr), shared-receiver{this}). + connect(std::forward<Sndr>(sndr), split-receiver{this}). 2. *Postcondition:* `waiting_states` is empty, and `completed` is `false`. @@ -8626,21 +8505,11 @@ namespace std::execution { dec-ref(). 6.
-          void detach() noexcept;
- - 1. *Effects:* If `completed` is `false` and `waiting_states` is empty, - calls `stop_src.request_stop()`. This has - the effect of requesting early termination of any asynchronous - operation that was started as a result of a call to `ensure_started`, - but only if the resulting sender was never connected and started. - - - 7.
           void inc-ref() noexcept;
1. *Effects:* Increments `ref_count`. - 8.
+      7. 
           void dec-ref() noexcept;
1. *Effects:* Decrements `ref_count`. If the new value of @@ -8650,39 +8519,34 @@ namespace std::execution { the `ref_count` to `0` then synchronizes with the call to dec-ref() that decrements `ref_count` to `0`. -8. For each type `split_t` and `ensure_started_t`, there is a different, - associated exposition-only implementation tag type, `split-impl-tag` - and `ensure-started-impl-tag`, respectively. Let - `shared-impl-tag` be the associated implementation tag type of - `shared-cpo`. Given an expression `sndr`, the expression - shared-cpo.transform_sender(sndr) is equivalent to: +8. Let `split-impl-tag` be an empty exposition-only class type. + Given an expression `sndr`, the expression + split.transform_sender(sndr) is equivalent to:
       auto&& [tag, _, child] = sndr;
       auto* sh_state = new shared-state{std::forward_like<decltype((sndr))>(child)};
-      return make-sender(shared-impl-tag(), shared-wrapper{sh_state, tag});
+      return make-sender(split-impl-tag(), shared-wrapper{sh_state, tag});
       
where `shared-wrapper` is an exposition-only class that manages the reference count of the `shared-state` object pointed to by `sh_state`. - `shared-wrapper` models `movable` with move operations nulling out the - moved-from object. If `tag` is `split_t`, `shared-wrapper` models - `copyable` with copy operations incrementing the reference count by calling - sh_state->inc-ref(). The constructor calls - sh_state->start-op() if `tag` is `ensure_started_t`. The - destructor has no effect if `sh_state` is null; otherwise, it calls - sh_state->detach() if `tag` is `ensure_started_t`; - and finally, it decrements the reference count by calling + `shared-wrapper` models `copyable` with move operations nulling out the + moved-from object, copy operations incrementing the reference count by calling + sh_state->inc-ref(), and assignment operations performing + a copy-and-swap operation. The + destructor has no effect if `sh_state` is null; otherwise, it + decrements the reference count by calling sh_state->dec-ref(). 9. The exposition-only class template `impls-for` - ([exec.snd.general]) is specialized for `shared-impl-tag` + ([exec.snd.general]) is specialized for `split-impl-tag` as follows:
         namespace std::execution {
           template<>
-          struct impls-for<shared-impl-tag> : default-impls {
+          struct impls-for<split-impl-tag> : default-impls {
             static constexpr auto get-state = see below;
             static constexpr auto start = see below;
           };
@@ -8690,7 +8554,7 @@ namespace std::execution {
         
1. The member - impls-for<shared-impl-tag>::get-state + impls-for<split-impl-tag>::get-state is initialized with a callable object equivalent to the following lambda expression: @@ -8701,7 +8565,7 @@ namespace std::execution {
2. The member - impls-for<shared-impl-tag>::start + impls-for<split-impl-tag>::start is initialized with a callable object that has a function call operator equivalent to the following: @@ -8723,37 +8587,19 @@ namespace std::execution { on-stop-request{state.sh_state->stop_src});
- 2. If `shared-impl-tag` is `ensure-started-impl-tag`, - and if `state.sh_state->stop_src.stop_requested()` is `true`, - calls `set_stopped(std::move(rcvr))` and returns. + 2. Then atomically does the following: - 3. Otherwise, atomically does the following: + - Reads the value `c` of `state.sh_state->completed`, and - - Inserts `addressof(state)` into `state.sh_state->waiting_states`, and + - Inserts `addressof(state)` into `state.sh_state->waiting_states` + if `c` is `false`. - - Reads the value of `state.sh_state->completed`. + 3. If `c` is `true`, calls state.notify() and returns. - 4. If the value read from `state.sh_state->completed` is `true`, - calls state.notify() and returns. - - 5. Otherwise, if `shared-impl-tag` is - `split-impl-tag`, and if `addressof(state)` is the first item added + 4. Otherwise, if `addressof(state)` is the first item added to `state.sh_state->waiting_states`, calls state.sh_state->start-op(). -10.
Under the following conditions, the results of the - child operation are discarded: - - - When a sender returned from `ensure_started` is destroyed without being - connected to a receiver, or - - - If the sender is connected to a receiver but the operation state - is destroyed without having been started, or - - - If polling the receiver's stop token indicates that stop has been - requested when `start` is called, and the operation has not yet - completed.
- #### `execution::when_all` [exec.when.all] #### {#spec-execution.senders.adaptor.when_all} 1. `when_all` and `when_all_with_variant` both adapt multiple input senders into @@ -9168,63 +9014,6 @@ namespace std::execution { ### Sender consumers [exec.consumers] ### {#spec-execution.senders.consumers} -#### `execution::start_detached` [exec.start.detached] #### {#spec-execution.senders.consumers.start_detached} - -1. `start_detached` eagerly starts a sender without the caller needing to manage - the lifetimes of any objects. - -2. The name `start_detached` denotes a customization point object. For a - subexpression `sndr`, let `Sndr` be `decltype((sndr))`. If - `sender_in` is `false`, `start_detached` is ill-formed. - Otherwise, the expression `start_detached(sndr)` is expression-equivalent to - the following except that `sndr` is evaluated only once: - -
-    apply_sender(get-domain-early(sndr), start_detached, sndr)
-    
- - * Mandates: same_as<decltype(e), void> is - `true` where e is the expression above. - - If the expression above does not eagerly start the sender `sndr` after - connecting it with a receiver that ignores value and stopped completion - operations and calls `terminate()` on error completions, the behavior of - calling `start_detached(sndr)` is undefined. - -3. Let `sndr` be a subexpression such that `Sndr` is `decltype((sndr))`, and let - `detached-receiver` and - `detached-operation` be the following exposition-only - class templates: - -
-    namespace std::execution {
-      template<class Sndr>
-      struct detached-receiver {
-        using receiver_concept = receiver_t;
-        detached-operation<Sndr>* op; // exposition only
-
-        void set_value() && noexcept { delete op; }
-        void set_error() && noexcept { terminate(); }
-        void set_stopped() && noexcept { delete op; }
-        empty_env get_env() const noexcept { return {}; }
-      };
-
-      template<class Sndr>
-      struct detached-operation {
-        connect_result_t<Sndr, detached-receiver<Sndr>> op; // exposition only
-
-        explicit detached-operation(Sndr&& sndr)
-          : op(connect(std::forward<Sndr>(sndr), detached-receiver<Sndr>{this}))
-        {}
-      };
-    }
-    
- -4. If sender_to<Sndr, detached-receiver<Sndr>> is `false`, the - expression `start_detached.apply_sender(sndr)` is ill-formed; otherwise, it is - expression-equivalent to start((new - detached-operation<Sndr>(sndr))->op). - #### `this_thread::sync_wait` [exec.sync.wait] #### {#spec-execution.senders.consumers.sync_wait} 1. `this_thread::sync_wait` and `this_thread::sync_wait_with_variant` are used @@ -9438,29 +9227,6 @@ namespace std::execution { 3. For a stopped completion, a disengaged `optional` object is returned. -## `execution::execute` [exec.execute] ## {#spec-execution.execute} - -1. `execute` executes a specified callable object on a specified scheduler. - -2. The name `execute` denotes a customization point object. For some - subexpressions `sch` and `f`, let `Sch` be `decltype((sch))` and `F` be the - decayed type of `f`. If `Sch` does not satisfy `scheduler` or `F` does not - satisfy `invocable`, `execute(sch, f)` is ill-formed. Otherwise, - `execute(sch, f)` is expression-equivalent to: - -
-    apply_sender(
-      query-or-default(get_domain, sch, default_domain()),
-      execute, schedule(sch), f)
-    
- - * Mandates: The type of the expression above is `void`. - -3. For some subexpressions `sndr` and `f` where `F` is the decayed type of `f`, - if `F` does not satisfy `invocable`, the expression - `execute.apply_sender(sndr, f)` is ill-formed; otherwise it is - expression-equivalent to `start_detached(then(sndr, f))`. - ## Sender/receiver utilities [exec.utils] ## {#spec-execution.snd_rec_utils} ### `execution::completion_signatures` [exec.utils.cmplsigs] ### {#spec-execution.snd_rec_utils.completion_sigs} From 59268fae941ce4f11ce52c811ed52ca9800c7031 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Thu, 27 Jun 2024 18:16:55 -0700 Subject: [PATCH 82/89] add the feature test macro `__cpp_lib_senders` (#258) --- execution.bs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index f7de51e..2a20d31 100644 --- a/execution.bs +++ b/execution.bs @@ -4035,8 +4035,34 @@ following new paragraph: +
+# Language support library [cpp] # {#spec-support} + + + +## Implementation properties [support.limits] ## {#spec-support.limits} + + + +### Header `` synopsis [version.syn] ### {#spec-version.syn} + +To the `` synopsis, add the following: + +
+#define __cpp_lib_semaphore       201907L         // also in <semaphore>
+#define __cpp_lib_senders         2024XXL         // also in <execution>
+#define __cpp_lib_shared_mutex    201505L         // also in <shared_mutex>
+
+ +
+ + } @@ -6932,13 +6962,6 @@ namespace std::execution { - Otherwise, `tag_of_t` is ill-formed. - - There is no way in standard C++ to determine whether the above declaration - is well-formed without causing a hard error, so this presumes compiler - magic. However, the author anticipates the adoption of [@P2141R1], which - makes it possible to implement this purely in the library. P2141 has already - been approved by EWG for C++26. - 6. Let `sender-for` be an exposition-only concept defined as follows:
@@ -7856,10 +7879,10 @@ namespace std::execution {
     * `decltype((sch))` does not satisfy `scheduler`, or
 
     * `decltype((sndr))` does not satisfy `sender` and `sndr` is not
-      a pipeable sender adaptor closure object ([exec.adapt.objects]), or
+        a pipeable sender adaptor closure object ([exec.adapt.objects]), or
 
     * `decltype((sndr))` satisfies `sender` and `sndr` is also
-      a pipeable sender adaptor closure object.
+        a pipeable sender adaptor closure object.
 
 3. Otherwise, if `decltype((sndr))` satisfies `sender`, the expression `on(sch,
     sndr)` is expression-equivalent to:
@@ -9955,6 +9978,20 @@ void finish();
         "pages": 2352,
         "publisher": "The Open Journal",
         "journal": "Journal of Open Source Software"
+    },
+
+    "P3175R3": {
+      "authors": ["Eric Niebler"],
+      "href": "https://wg21.link/P3175R3",
+      "title": "Reconsidering the std::execution::on algorithm",
+      "date": "2024-06-24"
+    },
+
+    "P3303R1": {
+      "authors": ["Eric Niebler"],
+      "href": "https://wg21.link/P3303R1",
+      "title": "Fixing Lazy Sender Algorithm Customization",
+      "date": "2024-06-24"
     }
 }
 
From c7abe75b885124cc573d0a4f1fadcec46b8a43de Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Fri, 28 Jun 2024 10:59:12 -0700 Subject: [PATCH 86/89] do not make term definitions (`dfn`) bold --- execution.bs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/execution.bs b/execution.bs index 6c8f298..9fe758e 100644 --- a/execution.bs +++ b/execution.bs @@ -167,6 +167,10 @@ div.hidden h6 { margin-block: 0; line-height: 0; } + +dfn { + font-weight: normal; +} # Introduction # {#intro} From 04215ba5ee88ab01a2283d476ac2755febde4d5c Mon Sep 17 00:00:00 2001 From: Lewis Baker Date: Thu, 4 Jul 2024 13:21:48 +0930 Subject: [PATCH 87/89] Fix typo in example: as_writeable_bytes -> as_writable_bytes Fixes #217 --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 6c8f298..ff4cc0b 100644 --- a/execution.bs +++ b/execution.bs @@ -389,7 +389,7 @@ struct dynamic_buffer { // sender_of auto async_read_array(auto handle) { // 2 return just(dynamic_buffer{}) // 4 | let_value([handle] (dynamic_buffer& buf) { // 5 - return just(std::as_writeable_bytes(std::span(&buf.size, 1))) // 6 + return just(std::as_writable_bytes(std::span(&buf.size, 1))) // 6 | async_read(handle) // 7 | then( // 8 [&buf] (std::size_t bytes_read) { // 9 From 12fde4af201017e49efd39178126f661a04dbb94 Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Sun, 7 Jul 2024 13:28:06 -0700 Subject: [PATCH 88/89] fix HTML escape issue --- execution.bs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/execution.bs b/execution.bs index 136d26a..6440161 100644 --- a/execution.bs +++ b/execution.bs @@ -1,9 +1,9 @@ @@ -9919,7 +9919,7 @@ void finish(); 2.
     template<class OtherPromise>
       requires (!same_as<OtherPromise, void>)
-    void set_continuation(coroutine_handle h) noexcept;
+    void set_continuation(coroutine_handle<OtherPromise> h) noexcept;
     
1. Effects: Equivalent to: From a1790ddda5dcdf70f0658d0b50794649caa6c96f Mon Sep 17 00:00:00 2001 From: Eric Niebler Date: Tue, 9 Jul 2024 15:30:11 -0700 Subject: [PATCH 89/89] fix revision number to be purely numeric --- execution.bs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/execution.bs b/execution.bs index 6440161..8ce69d2 100644 --- a/execution.bs +++ b/execution.bs @@ -2,7 +2,7 @@ Title: `std::execution` H1: std::execution Shortname: D2300 -Revision: 10.a +Revision: 11 Status: D Group: WG21 Date: 2024-06-28