LCOV - code coverage report
Current view: top level - capy/ex - async_event.hpp (source / functions) Coverage Total Hit
Test: coverage_remapped.info Lines: 100.0 % 84 84
Test Date: 2026-11-25 23:19:07 Functions: 100.0 % 15 15

           TLA  Line data    Source code
       1                 : //
       2                 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
       3                 : // Copyright (c) 2026 Michael Vandeberg
       4                 : //
       5                 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
       6                 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
       7                 : //
       8                 : // Official repository: https://github.com/cppalliance/capy
       9                 : //
      10                 : 
      11                 : #ifndef BOOST_CAPY_ASYNC_EVENT_HPP
      12                 : #define BOOST_CAPY_ASYNC_EVENT_HPP
      13                 : 
      14                 : #include <boost/capy/detail/config.hpp>
      15                 : #include <boost/capy/detail/intrusive.hpp>
      16                 : #include <boost/capy/continuation.hpp>
      17                 : #include <boost/capy/concept/executor.hpp>
      18                 : #include <boost/capy/error.hpp>
      19                 : #include <boost/capy/ex/await_context.hpp>
      20                 : #include <boost/capy/results.hpp>
      21                 : 
      22                 : #include <stop_token>
      23                 : 
      24                 : #include <atomic>
      25                 : #include <coroutine>
      26                 : #include <new>
      27                 : #include <utility>
      28                 : 
      29                 : /*  async_event implementation notes
      30                 :     =================================
      31                 : 
      32                 :     Same cancellation pattern as async_mutex (see that file for the
      33                 :     full discussion on claimed_, stop_cb lifetime, member ordering,
      34                 :     and threading assumptions).
      35                 : 
      36                 :     Key difference: set() wakes ALL waiters (broadcast), not one.
      37                 :     It pops every waiter from the list and posts the ones it
      38                 :     claims. Waiters already claimed by a stop callback are skipped.
      39                 : 
      40                 :     Because set() pops all waiters, a canceled waiter may have been
      41                 :     removed from the list by set() before its await_resume runs. Each
      42                 :     waiter therefore records the list it is linked into, if any: the
      43                 :     event's, or set()'s own while set() posts the waiters it claimed.
      44                 :     A waiter destroyed or canceled while linked unlinks itself from
      45                 :     that list, so a post that tears down one claimed waiter, and with
      46                 :     it another, never leaves set() holding a freed node.
      47                 : 
      48                 :     Only the post is subject to the claim race. A losing stop
      49                 :     callback does nothing, but set() unlinks every waiter it pops
      50                 :     whether it claims it or not. That is why await_resume unlinks a
      51                 :     canceled waiter only when it is still linked.
      52                 : */
      53                 : 
      54                 : namespace boost {
      55                 : namespace capy {
      56                 : 
      57                 : /** Queues coroutines in `wait()` and resumes all of them when `set()` is called.
      58                 : 
      59                 :     This event provides a way to notify multiple coroutines that some
      60                 :     condition has occurred. When a coroutine awaits an unset event, it
      61                 :     suspends and is added to a wait queue. When the event is set, all
      62                 :     waiting coroutines are resumed.
      63                 : 
      64                 :     @par Cancellation
      65                 : 
      66                 :     When a coroutine is suspended waiting for the event and its stop
      67                 :     token is triggered, the waiter completes with `error::canceled`
      68                 :     instead of waiting for `set()`.
      69                 : 
      70                 :     If the event is already set, `wait()` completes successfully
      71                 :     without consulting the stop token. Otherwise a pending stop request
      72                 :     completes the wait with `error::canceled`. When a stop request races
      73                 :     with `set()`, whichever reaches the waiter first decides the result.
      74                 : 
      75                 :     @par Zero Allocation
      76                 : 
      77                 :     No heap allocation occurs for wait operations.
      78                 : 
      79                 :     @par Thread Safety
      80                 : 
      81                 :     Distinct objects: Safe.@n
      82                 :     Shared objects: Unsafe.
      83                 : 
      84                 :     The event operations are designed for single-threaded use on one
      85                 :     executor. The stop callback may fire from any thread.
      86                 : 
      87                 :     This type is non-copyable and non-movable because suspended
      88                 :     waiters hold intrusive pointers into the event's internal list.
      89                 : 
      90                 :     @par Example
      91                 :     @par !example example
      92                 : 
      93                 : */
      94                 : class async_event
      95                 : {
      96                 : public:
      97                 :     class wait_awaiter;
      98                 : 
      99                 : private:
     100                 :     bool set_ = false;
     101                 :     detail::intrusive_list<wait_awaiter> waiters_;
     102                 : 
     103                 :     // Unlink every waiter and move the ones this call claims into into.
     104                 :     void claim_all(detail::intrusive_list<wait_awaiter>& into) noexcept;
     105                 : 
     106                 : public:
     107                 :     /** Suspends the caller until `set()` runs, or resumes it with `error::canceled` on a stop request.
     108                 :     */
     109                 :     class wait_awaiter
     110                 :         : public detail::intrusive_list<wait_awaiter>::node
     111                 :     {
     112                 :         friend class async_event;
     113                 : 
     114                 :         async_event* e_;
     115                 :         continuation cont_;
     116                 :         executor_ref ex_;
     117                 : 
     118                 :         // Declared before stop_cb_buf_: the callback
     119                 :         // accesses these members, so they must still be
     120                 :         // alive if the stop_cb_ destructor blocks.
     121                 :         std::atomic<bool> claimed_{false};
     122                 :         bool canceled_ = false;
     123                 :         bool active_ = false;
     124                 :         detail::intrusive_list<wait_awaiter>* list_ = nullptr;
     125                 : 
     126                 :         struct cancel_fn
     127                 :         {
     128                 :             wait_awaiter* self_;
     129                 : 
     130 HIT           9 :             void operator()() const noexcept
     131                 :             {
     132               9 :                 if(!self_->claimed_.exchange(
     133                 :                     true, std::memory_order_acq_rel))
     134                 :                 {
     135               8 :                     self_->canceled_ = true;
     136               8 :                     self_->ex_.post(self_->cont_);
     137                 :                 }
     138               9 :             }
     139                 :         };
     140                 : 
     141                 :         using stop_cb_t =
     142                 :             std::stop_callback<cancel_fn>;
     143                 : 
     144                 :         // Aligned storage for stop_cb_t. Declared last:
     145                 :         // its destructor may block while the callback
     146                 :         // accesses the members above.
     147                 :         BOOST_CAPY_MSVC_WARNING_PUSH
     148                 :         BOOST_CAPY_MSVC_WARNING_DISABLE(4324) // padded due to alignas
     149                 :         alignas(stop_cb_t)
     150                 :             unsigned char stop_cb_buf_[sizeof(stop_cb_t)];
     151                 :         BOOST_CAPY_MSVC_WARNING_POP
     152                 : 
     153              93 :         stop_cb_t& stop_cb_() noexcept
     154                 :         {
     155                 :             return *reinterpret_cast<stop_cb_t*>(
     156              93 :                 stop_cb_buf_);
     157                 :         }
     158                 : 
     159                 :     public:
     160                 :         /** Destroy the awaiter, leaving the event unable to reach it.
     161                 : 
     162                 :             Destroys the stop callback if one is registered, and unlinks
     163                 :             the awaiter from the event's wait queue if it is still linked.
     164                 :             Both are necessary when the coroutine frame is torn down while
     165                 :             suspended, so that neither `set()` nor the stop callback can
     166                 :             reach a destroyed awaiter.
     167                 :         */
     168             200 :         ~wait_awaiter()
     169                 :         {
     170             200 :             if(active_)
     171              41 :                 stop_cb_().~stop_cb_t();
     172             200 :             if(list_)
     173               5 :                 list_->remove(this);
     174             200 :         }
     175                 : 
     176                 :         /** Construct an awaiter for the given event.
     177                 : 
     178                 :             @param e The event to wait on. It must outlive the awaiter.
     179                 :         */
     180             100 :         explicit wait_awaiter(async_event* e) noexcept
     181             100 :             : e_(e)
     182                 :         {
     183             100 :         }
     184                 : 
     185                 :         /** Construct by moving.
     186                 : 
     187                 :             The moved-from awaiter is left inert: its destructor no longer
     188                 :             destroys the stop callback and no longer unlinks from the
     189                 :             event's wait queue.
     190                 : 
     191                 :             @pre The source has not been suspended (its `await_suspend`
     192                 :             has not enqueued it).
     193                 : 
     194                 :             @param o The awaiter to move from.
     195                 :         */
     196             100 :         wait_awaiter(wait_awaiter&& o) noexcept
     197             200 :             : e_(o.e_)
     198             100 :             , cont_(o.cont_)
     199             100 :             , ex_(o.ex_)
     200             100 :             , claimed_(o.claimed_.load(
     201                 :                 std::memory_order_relaxed))
     202             100 :             , canceled_(o.canceled_)
     203             100 :             , active_(std::exchange(o.active_, false))
     204             200 :             , list_(std::exchange(o.list_, nullptr))
     205                 :         {
     206             100 :         }
     207                 : 
     208                 :         /** Deleted: a waiter is linked into the event's queue by address.
     209                 : 
     210                 :             @param other The awaiter that would be copied.
     211                 :         */
     212                 :         wait_awaiter(wait_awaiter const& other) = delete;
     213                 : 
     214                 :         /** Deleted: a waiter is linked into the event's queue by address.
     215                 : 
     216                 :             @param other The awaiter that would be assigned from.
     217                 : 
     218                 :             @return A reference to `*this`.
     219                 :         */
     220                 :         wait_awaiter& operator=(wait_awaiter const& other) = delete;
     221                 : 
     222                 :         /** Deleted: a waiter is linked into the event's queue by address.
     223                 : 
     224                 :             @param other The awaiter that would be moved from.
     225                 : 
     226                 :             @return A reference to `*this`.
     227                 :         */
     228                 :         wait_awaiter& operator=(wait_awaiter&& other) = delete;
     229                 : 
     230                 :         /** Check whether the event is already set.
     231                 : 
     232                 :             If the event is set, the awaiting coroutine does not suspend.
     233                 : 
     234                 :             @return `true` if the event is set; otherwise `false`.
     235                 :         */
     236             100 :         bool await_ready() const noexcept
     237                 :         {
     238             100 :             return e_->set_;
     239                 :         }
     240                 : 
     241                 :         /** Enqueue the awaiting coroutine until the event is set.
     242                 : 
     243                 :             This is the @ref ContextAwaitable overload of `await_suspend`.
     244                 : 
     245                 :             If a stop request is already pending on `env->stop_token`, the
     246                 :             awaiter records the cancellation and does not enqueue.
     247                 : 
     248                 :             Otherwise it stores `h` and `env->executor`, links itself into
     249                 :             the event's wait queue, and registers a stop callback on
     250                 :             `env->stop_token`. Exactly one of `set()`, that callback, and
     251                 :             the event's destructor posts `h` through the stored executor.
     252                 :             Whichever claims the waiter first does so.
     253                 : 
     254                 :             @param h The awaiting coroutine, resumed when the event is set
     255                 :             or the wait is canceled.
     256                 : 
     257                 :             @param env The execution environment. Its executor posts the
     258                 :             resumption and its stop token is watched for the duration of
     259                 :             the wait. It must outlive the wait.
     260                 : 
     261                 :             A returned `h` resumes the awaiting coroutine at once without
     262                 :             enqueuing it. A returned `std::noop_coroutine()` leaves the
     263                 :             coroutine suspended and returns control to the resumer.
     264                 : 
     265                 :             @return `h` if stop was already requested, else `noop_coroutine()`.
     266                 :         */
     267                 :         std::coroutine_handle<>
     268              95 :         await_suspend(
     269                 :             std::coroutine_handle<> h,
     270                 :             await_context const* env) noexcept
     271                 :         {
     272              95 :             if(env->stop_token.stop_requested())
     273                 :             {
     274               2 :                 canceled_ = true;
     275               2 :                 return h;
     276                 :             }
     277              93 :             cont_.h = h;
     278              93 :             cont_.owner = env->owner;
     279              93 :             ex_ = env->executor;
     280              93 :             e_->waiters_.push_back(this);
     281              93 :             list_ = &e_->waiters_;
     282             279 :             ::new(stop_cb_buf_) stop_cb_t(
     283              93 :                 env->stop_token, cancel_fn{this});
     284              93 :             active_ = true;
     285              93 :             return std::noop_coroutine();
     286                 :         }
     287                 : 
     288                 :         /** Complete the wait and report the outcome.
     289                 : 
     290                 :             Destroys the stop callback if one is registered, and leaves
     291                 :             the awaiter unlinked from the event's wait queue.
     292                 : 
     293                 :             @return Empty on set, else `error::canceled` (stop or destruction).
     294                 :         */
     295              57 :         [[nodiscard]] results<> await_resume() noexcept
     296                 :         {
     297              57 :             if(active_)
     298                 :             {
     299              52 :                 stop_cb_().~stop_cb_t();
     300              52 :                 active_ = false;
     301                 :             }
     302              57 :             if(canceled_)
     303                 :             {
     304              38 :                 if(list_)
     305                 :                 {
     306               3 :                     list_->remove(this);
     307               3 :                     list_ = nullptr;
     308                 :                 }
     309              76 :                 return {make_error_code(
     310              38 :                     error::canceled)};
     311                 :             }
     312              19 :             return {{}};
     313                 :         }
     314                 :     };
     315                 : 
     316                 :     /// Construct an unset event.
     317               2 :     async_event() = default;
     318                 : 
     319                 :     /** Deleted: suspended waiters point into the event's wait queue.
     320                 : 
     321                 :         @param other The event that would be copied.
     322                 :     */
     323                 :     async_event(async_event const& other) = delete;
     324                 : 
     325                 :     /** Deleted: suspended waiters point into the event's wait queue.
     326                 : 
     327                 :         @param other The event that would be assigned from.
     328                 : 
     329                 :         @return A reference to `*this`.
     330                 :     */
     331                 :     async_event& operator=(async_event const& other) = delete;
     332                 : 
     333                 :     /** Deleted: suspended waiters point into the event's wait queue.
     334                 : 
     335                 :         @param other The event that would be moved from.
     336                 :     */
     337                 :     async_event(async_event&& other) = delete;
     338                 : 
     339                 :     /** Deleted: suspended waiters point into the event's wait queue.
     340                 : 
     341                 :         @param other The event that would be moved from.
     342                 : 
     343                 :         @return A reference to `*this`.
     344                 :     */
     345                 :     async_event& operator=(async_event&& other) = delete;
     346                 : 
     347                 :     /** Destroy the event, canceling every coroutine still waiting.
     348                 : 
     349                 :         Each waiter is posted to its executor to resume with
     350                 :         `error::canceled`, as if its stop token had been triggered. An
     351                 :         executor that can no longer run it abandons it instead, possibly
     352                 :         before this destructor returns. Either way the waiter no longer
     353                 :         refers to the event.
     354                 :     */
     355              30 :     ~async_event()
     356                 :     {
     357              97 :         while(auto* w = waiters_.pop_front())
     358                 :         {
     359              67 :             w->list_ = nullptr;
     360              67 :             if(!w->claimed_.exchange(true, std::memory_order_acq_rel))
     361                 :             {
     362              66 :                 w->canceled_ = true;
     363              66 :                 w->ex_.post(w->cont_);
     364                 :             }
     365              67 :         }
     366              30 :     }
     367                 : 
     368                 :     /** Return an awaiter that waits until the event is set.
     369                 : 
     370                 :         If the event is already set, completes immediately.
     371                 : 
     372                 :         @return An awaitable that await-returns `(error_code)`.
     373                 :     */
     374             100 :     wait_awaiter wait() noexcept
     375                 :     {
     376             100 :         return wait_awaiter{this};
     377                 :     }
     378                 : 
     379                 :     /** Post every waiting coroutine to its executor and mark the event set.
     380                 : 
     381                 :         Each waiting coroutine is posted to its executor. Canceled waiters
     382                 :         are skipped. Subsequent calls to wait() complete
     383                 :         immediately until clear() is called.
     384                 : 
     385                 :         @note If posting a waiter's resumption throws, `std::terminate`
     386                 :         is called.
     387                 :     */
     388              20 :     void set() noexcept
     389                 :     {
     390              20 :         set_ = true;
     391                 :         // A post can destroy a waiter on the spot, and with it whatever
     392                 :         // owns this event; nothing below touches *this.
     393              20 :         detail::intrusive_list<wait_awaiter> claimed;
     394              20 :         claim_all(claimed);
     395              38 :         while(auto* w = claimed.pop_front())
     396                 :         {
     397              18 :             w->list_ = nullptr;
     398              18 :             w->ex_.post(w->cont_);
     399              18 :         }
     400              20 :     }
     401                 : 
     402                 :     /** Clear the event.
     403                 : 
     404                 :         Subsequent calls to wait() suspend until
     405                 :         set() is called again.
     406                 :     */
     407               2 :     void clear() noexcept
     408                 :     {
     409               2 :         set_ = false;
     410               2 :     }
     411                 : 
     412                 :     /** Check whether the event is currently set.
     413                 : 
     414                 :         @return `true` if the event is set; otherwise `false`.
     415                 :     */
     416               9 :     bool is_set() const noexcept
     417                 :     {
     418               9 :         return set_;
     419                 :     }
     420                 : };
     421                 : 
     422                 : inline void
     423              20 : async_event::claim_all(
     424                 :     detail::intrusive_list<wait_awaiter>& into) noexcept
     425                 : {
     426              38 :     while(auto* w = waiters_.pop_front())
     427                 :     {
     428              18 :         w->list_ = nullptr;
     429              18 :         if(!w->claimed_.exchange(true, std::memory_order_acq_rel))
     430                 :         {
     431              18 :             into.push_back(w);
     432              18 :             w->list_ = &into;
     433                 :         }
     434              18 :     }
     435              20 : }
     436                 : 
     437                 : } // namespace capy
     438                 : } // namespace boost
     439                 : 
     440                 : #endif
        

Generated by: LCOV version 2.3