100.00% Lines (135/135) 100.00% Functions (23/23)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com) 2   // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3   // Copyright (c) 2026 Michael Vandeberg 3   // Copyright (c) 2026 Michael Vandeberg
4   // 4   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 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) 6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 7   //
8   // Official repository: https://github.com/cppalliance/capy 8   // Official repository: https://github.com/cppalliance/capy
9   // 9   //
10   10  
11   #ifndef BOOST_CAPY_ASYNC_MUTEX_HPP 11   #ifndef BOOST_CAPY_ASYNC_MUTEX_HPP
12   #define BOOST_CAPY_ASYNC_MUTEX_HPP 12   #define BOOST_CAPY_ASYNC_MUTEX_HPP
13   13  
14   #include <boost/capy/detail/config.hpp> 14   #include <boost/capy/detail/config.hpp>
15   #include <boost/capy/detail/intrusive.hpp> 15   #include <boost/capy/detail/intrusive.hpp>
16   #include <boost/capy/continuation.hpp> 16   #include <boost/capy/continuation.hpp>
17   #include <boost/capy/concept/executor.hpp> 17   #include <boost/capy/concept/executor.hpp>
18   #include <boost/capy/error.hpp> 18   #include <boost/capy/error.hpp>
19   #include <boost/capy/ex/await_context.hpp> 19   #include <boost/capy/ex/await_context.hpp>
20   #include <boost/capy/results.hpp> 20   #include <boost/capy/results.hpp>
21   21  
22   #include <stop_token> 22   #include <stop_token>
23   23  
24   #include <atomic> 24   #include <atomic>
25   #include <coroutine> 25   #include <coroutine>
26   #include <new> 26   #include <new>
27   #include <utility> 27   #include <utility>
28   28  
29   /* async_mutex implementation notes 29   /* async_mutex implementation notes
30   ================================ 30   ================================
31   31  
32   Waiters form a doubly-linked intrusive list (fair FIFO). lock_awaiter 32   Waiters form a doubly-linked intrusive list (fair FIFO). lock_awaiter
33   inherits intrusive_list<lock_awaiter>::node; the list is owned by 33   inherits intrusive_list<lock_awaiter>::node; the list is owned by
34   async_mutex::waiters_. 34   async_mutex::waiters_.
35   35  
36   Cancellation via stop_token 36   Cancellation via stop_token
37   --------------------------- 37   ---------------------------
38   A std::stop_callback is registered in await_suspend. Two actors can 38   A std::stop_callback is registered in await_suspend. Two actors can
39   race to resume the suspended coroutine: unlock() and the stop callback. 39   race to resume the suspended coroutine: unlock() and the stop callback.
40   An atomic bool `claimed_` resolves the race -- whoever does 40   An atomic bool `claimed_` resolves the race -- whoever does
41   claimed_.exchange(true) and reads false wins. The loser does nothing. 41   claimed_.exchange(true) and reads false wins. The loser does nothing.
42   42  
43 - The stop callback calls ex_.post(h_). The stop_callback is 43 + The stop callback calls ex_.post(cont_). The stop_callback is
44   destroyed later in await_resume. cancel_fn touches no members 44   destroyed later in await_resume. cancel_fn touches no members
45   after post returns (same pattern as delete-this). 45   after post returns (same pattern as delete-this).
46   46  
47   unlock() pops waiters from the front. If the popped waiter was 47   unlock() pops waiters from the front. If the popped waiter was
48   already claimed by the stop callback, unlock() skips it and tries 48   already claimed by the stop callback, unlock() skips it and tries
49   the next. await_resume removes the (still-linked) canceled waiter 49   the next. await_resume removes the (still-linked) canceled waiter
50   via waiters_.remove(this). 50   via waiters_.remove(this).
51   51  
52 - The stop_callback lives in a union to suppress automatic 52 + The stop_callback lives in the aligned byte buffer stop_cb_buf_ to
53 - construction/destruction. Placement new in await_suspend, explicit 53 + suppress automatic construction/destruction. Placement new in
54 - destructor call in await_resume and ~lock_awaiter. 54 + await_suspend, explicit destructor call in await_resume and
  55 + ~lock_awaiter.
55   56  
56   Member ordering constraint 57   Member ordering constraint
57   -------------------------- 58   --------------------------
58 - The union containing stop_cb_ must be declared AFTER the members 59 + stop_cb_buf_ must be declared AFTER the members the callback
59 - the callback accesses (h_, ex_, claimed_, canceled_). If the 60 + accesses (cont_, ex_, claimed_, canceled_). If the stop_cb_
60 - stop_cb_ destructor blocks waiting for a concurrent callback, those 61 + destructor blocks waiting for a concurrent callback, those members
61 - members must still be alive (C++ destroys in reverse declaration 62 + must still be alive (C++ destroys in reverse declaration order).
62 - order).  
63   63  
64 - active_ flag 64 + active_, in_list_ and granted_ flags
65 - ------------ 65 + ------------------------------------
66 - Tracks both list membership and stop_cb_ lifetime (they are always 66 + active_ tracks stop_cb_ lifetime. in_list_ tracks list membership;
67 - set and cleared together). Used by the destructor to clean up if the 67 + whoever pops the node (unlock() or ~async_mutex) clears it, so it
68 - coroutine is destroyed while suspended (e.g. execution_context 68 + can be false while active_ is still true. granted_ marks a waiter
69 - shutdown). 69 + handed the lock but not yet resumed. The destructor uses all three
  70 + to clean up if the coroutine is destroyed while suspended (e.g.
  71 + execution_context shutdown).
70   72  
71   Cancellation scope 73   Cancellation scope
72   ------------------ 74   ------------------
73 - Cancellation only takes effect while the coroutine is suspended in 75 + If the mutex is unlocked, await_ready acquires it immediately
74 - the wait queue. If the mutex is unlocked, await_ready acquires it 76 + without checking the stop token. This is intentional: the fast path
75 - immediately without checking the stop token. This is intentional: 77 + has no token access and no overhead. Otherwise await_suspend
76 - the fast path has no token access and no overhead. 78 + cancels on a stop request already pending, without enqueuing, and
  79 + the stop callback cancels a later one.
77   80  
78   Threading assumptions 81   Threading assumptions
79   --------------------- 82   ---------------------
80   - All list mutations happen on the executor thread (await_suspend, 83   - All list mutations happen on the executor thread (await_suspend,
81   await_resume, unlock, ~lock_awaiter). 84   await_resume, unlock, ~lock_awaiter).
82   - The stop callback may fire from any thread, but only touches 85   - The stop callback may fire from any thread, but only touches
83   claimed_ (atomic) and then calls post. It never touches the 86   claimed_ (atomic) and then calls post. It never touches the
84   list. 87   list.
85   - ~lock_awaiter must be called from the executor thread. This is 88   - ~lock_awaiter must be called from the executor thread. This is
86   guaranteed during normal shutdown but NOT if the coroutine frame 89   guaranteed during normal shutdown but NOT if the coroutine frame
87   is destroyed from another thread while a stop callback could 90   is destroyed from another thread while a stop callback could
88   fire (precondition violation, same as cppcoro/folly). 91   fire (precondition violation, same as cppcoro/folly).
89   */ 92   */
90   93  
91   namespace boost { 94   namespace boost {
92   namespace capy { 95   namespace capy {
93   96  
94   /** Queues coroutines in `lock()` and resumes exactly one when the mutex is free. 97   /** Queues coroutines in `lock()` and resumes exactly one when the mutex is free.
95   98  
96   This mutex provides mutual exclusion for coroutines without blocking. 99   This mutex provides mutual exclusion for coroutines without blocking.
97   When a coroutine attempts to acquire a locked mutex, it suspends and 100   When a coroutine attempts to acquire a locked mutex, it suspends and
98   is added to an intrusive wait queue. When the holder unlocks, the next 101   is added to an intrusive wait queue. When the holder unlocks, the next
99   waiter is resumed with the lock held. 102   waiter is resumed with the lock held.
100   103  
101   @par Cancellation 104   @par Cancellation
102   105  
103   When a coroutine is suspended waiting for the mutex and its stop 106   When a coroutine is suspended waiting for the mutex and its stop
104   token is triggered, the waiter completes with `error::canceled` 107   token is triggered, the waiter completes with `error::canceled`
105   instead of acquiring the lock. 108   instead of acquiring the lock.
106   109  
107 - Cancellation only applies while the coroutine is suspended in the 110 + If the mutex is unlocked, `lock()` acquires it without consulting
108 - wait queue. If the mutex is unlocked when `lock()` is called, the 111 + the stop token. Otherwise a pending stop request completes the wait
109 - lock is acquired immediately even if the stop token is already 112 + with `error::canceled`. When a stop request races with `unlock()`,
110 - signaled. 113 + whichever reaches the waiter first decides the result. If the mutex
  114 + is destroyed before a granted waiter resumes, that waiter completes
  115 + with `error::canceled` instead.
111   116  
112   @par Zero Allocation 117   @par Zero Allocation
113   118  
114   No heap allocation occurs for lock operations. 119   No heap allocation occurs for lock operations.
115   120  
116   @par Thread Safety 121   @par Thread Safety
117   122  
118   Distinct objects: Safe.@n 123   Distinct objects: Safe.@n
119   Shared objects: Unsafe. 124   Shared objects: Unsafe.
120   125  
121   The mutex operations are designed for single-threaded use on one 126   The mutex operations are designed for single-threaded use on one
122   executor. The stop callback may fire from any thread. 127   executor. The stop callback may fire from any thread.
123   128  
124   This type is non-copyable and non-movable because suspended 129   This type is non-copyable and non-movable because suspended
125   waiters hold intrusive pointers into the mutex's internal list. 130   waiters hold intrusive pointers into the mutex's internal list.
126   131  
127   @par Example 132   @par Example
128   @par !example example 133   @par !example example
129   134  
130   */ 135   */
131   class async_mutex 136   class async_mutex
132   { 137   {
133   public: 138   public:
134   class lock_awaiter; 139   class lock_awaiter;
135   class lock_guard; 140   class lock_guard;
136   class lock_guard_awaiter; 141   class lock_guard_awaiter;
137   142  
138   private: 143   private:
139   bool locked_ = false; 144   bool locked_ = false;
140   detail::intrusive_list<lock_awaiter> waiters_; 145   detail::intrusive_list<lock_awaiter> waiters_;
141   // Handed the lock but not yet resumed; the destructor must reach it. 146   // Handed the lock but not yet resumed; the destructor must reach it.
142   lock_awaiter* granted_to_ = nullptr; 147   lock_awaiter* granted_to_ = nullptr;
143   148  
144   // State of the unlock() in progress, on its own stack: a post can 149   // State of the unlock() in progress, on its own stack: a post can
145   // destroy the granted waiter, re-entering unlock(), or this mutex. 150   // destroy the granted waiter, re-entering unlock(), or this mutex.
146   struct unlock_scope 151   struct unlock_scope
147   { 152   {
148   bool again = false; 153   bool again = false;
149   bool gone = false; 154   bool gone = false;
150   }; 155   };
151   unlock_scope* unlocking_ = nullptr; 156   unlock_scope* unlocking_ = nullptr;
152   157  
153   public: 158   public:
154   /** Suspends the caller until the mutex is free, or resumes it with `error::canceled` on a stop request. 159   /** Suspends the caller until the mutex is free, or resumes it with `error::canceled` on a stop request.
155   */ 160   */
156   class lock_awaiter 161   class lock_awaiter
157   : public detail::intrusive_list<lock_awaiter>::node 162   : public detail::intrusive_list<lock_awaiter>::node
158   { 163   {
159   friend class async_mutex; 164   friend class async_mutex;
160   165  
161   async_mutex* m_; 166   async_mutex* m_;
162   continuation cont_; 167   continuation cont_;
163   executor_ref ex_; 168   executor_ref ex_;
164   169  
165 - // These members must be declared before stop_cb_ 170 + // These members must be declared before stop_cb_buf_
166 - // (see comment on the union below). 171 + // (see the comment on it below).
167   std::atomic<bool> claimed_{false}; 172   std::atomic<bool> claimed_{false};
168   bool canceled_ = false; 173   bool canceled_ = false;
169   bool active_ = false; 174   bool active_ = false;
170   175  
171   // Set by unlock() when it hands the lock to this waiter. 176   // Set by unlock() when it hands the lock to this waiter.
172   bool granted_ = false; 177   bool granted_ = false;
173   178  
174   // Cleared by whoever pops the node, so a waiter outliving 179   // Cleared by whoever pops the node, so a waiter outliving
175   // its mutex never reaches through m_. 180   // its mutex never reaches through m_.
176   bool in_list_ = false; 181   bool in_list_ = false;
177   182  
178   struct cancel_fn 183   struct cancel_fn
179   { 184   {
180   lock_awaiter* self_; 185   lock_awaiter* self_;
181   186  
HITCBC 182   8 void operator()() const noexcept 187   8 void operator()() const noexcept
183   { 188   {
HITCBC 184   8 if(!self_->claimed_.exchange( 189   8 if(!self_->claimed_.exchange(
185   true, std::memory_order_acq_rel)) 190   true, std::memory_order_acq_rel))
186   { 191   {
HITCBC 187   8 self_->canceled_ = true; 192   8 self_->canceled_ = true;
HITCBC 188   8 self_->ex_.post(self_->cont_); 193   8 self_->ex_.post(self_->cont_);
189   } 194   }
HITCBC 190   8 } 195   8 }
191   }; 196   };
192   197  
193   using stop_cb_t = 198   using stop_cb_t =
194   std::stop_callback<cancel_fn>; 199   std::stop_callback<cancel_fn>;
195   200  
196   // Aligned storage for stop_cb_t. Declared last: 201   // Aligned storage for stop_cb_t. Declared last:
197   // its destructor may block while the callback 202   // its destructor may block while the callback
198   // accesses the members above. 203   // accesses the members above.
199   BOOST_CAPY_MSVC_WARNING_PUSH 204   BOOST_CAPY_MSVC_WARNING_PUSH
200   BOOST_CAPY_MSVC_WARNING_DISABLE(4324) // padded due to alignas 205   BOOST_CAPY_MSVC_WARNING_DISABLE(4324) // padded due to alignas
201   alignas(stop_cb_t) 206   alignas(stop_cb_t)
202   unsigned char stop_cb_buf_[sizeof(stop_cb_t)]; 207   unsigned char stop_cb_buf_[sizeof(stop_cb_t)];
203   BOOST_CAPY_MSVC_WARNING_POP 208   BOOST_CAPY_MSVC_WARNING_POP
204   209  
HITCBC 205   100026 stop_cb_t& stop_cb_() noexcept 210   100026 stop_cb_t& stop_cb_() noexcept
206   { 211   {
207   return *reinterpret_cast<stop_cb_t*>( 212   return *reinterpret_cast<stop_cb_t*>(
HITCBC 208   100026 stop_cb_buf_); 213   100026 stop_cb_buf_);
209   } 214   }
210   215  
211   public: 216   public:
212   /** Destroy the awaiter, leaving the mutex unable to reach it. 217   /** Destroy the awaiter, leaving the mutex unable to reach it.
213   218  
214   If the awaiter is suspended in the wait queue, destroys the 219   If the awaiter is suspended in the wait queue, destroys the
215   stop callback and unlinks the awaiter. Neither `unlock()` nor 220   stop callback and unlinks the awaiter. Neither `unlock()` nor
216   the stop callback can then reach a destroyed awaiter when the 221   the stop callback can then reach a destroyed awaiter when the
217   coroutine frame is torn down while suspended. 222   coroutine frame is torn down while suspended.
218   223  
219   If the lock was handed to this awaiter and the coroutine is 224   If the lock was handed to this awaiter and the coroutine is
220   destroyed before it resumes, the lock is released to the next 225   destroyed before it resumes, the lock is released to the next
221   waiter. 226   waiter.
222   227  
223 - @par Preconditions 228 + @pre Called on the executor thread. The stop callback may fire
224 - Called on the executor thread. The stop callback may fire from 229 + from any thread, so destroying a still-suspended awaiter from
225 - any thread, so destroying a still-suspended awaiter from  
226   another thread is undefined. 230   another thread is undefined.
227   */ 231   */
HITCBC 228   200099 ~lock_awaiter() 232   200099 ~lock_awaiter()
229   { 233   {
HITCBC 230   200099 if(active_) 234   200099 if(active_)
231   { 235   {
HITCBC 232   100009 stop_cb_().~stop_cb_t(); 236   100009 stop_cb_().~stop_cb_t();
233   } 237   }
HITCBC 234   200099 if(in_list_) 238   200099 if(in_list_)
HITCBC 235   3 m_->waiters_.remove(this); 239   3 m_->waiters_.remove(this);
236   // Handed the lock but destroyed before resuming: pass it on. 240   // Handed the lock but destroyed before resuming: pass it on.
HITCBC 237   200099 if(granted_) 241   200099 if(granted_)
238   { 242   {
HITCBC 239   100002 m_->granted_to_ = nullptr; 243   100002 m_->granted_to_ = nullptr;
HITCBC 240   100002 m_->unlock(); 244   100002 m_->unlock();
241   } 245   }
HITCBC 242   200099 } 246   200099 }
243   247  
244   /** Construct an awaiter for the given mutex. 248   /** Construct an awaiter for the given mutex.
245   249  
246 - @param m The mutex to acquire. It must outlive the awaiter. 250 + @param m The mutex to acquire. It must outlive the awaiter,
  251 + unless the mutex's destructor runs while the awaiter is
  252 + suspended. The destructor then cancels the awaiter.
247   */ 253   */
HITCBC 248   100052 explicit lock_awaiter(async_mutex* m) noexcept 254   100052 explicit lock_awaiter(async_mutex* m) noexcept
HITCBC 249   100052 : m_(m) 255   100052 : m_(m)
250   { 256   {
HITCBC 251   100052 } 257   100052 }
252   258  
253   /** Construct by moving. 259   /** Construct by moving.
254   260  
255   The moved-from awaiter is left inert: its destructor no longer 261   The moved-from awaiter is left inert: its destructor no longer
256   destroys the stop callback and no longer unlinks from the 262   destroys the stop callback and no longer unlinks from the
257   mutex's wait queue. 263   mutex's wait queue.
258   264  
  265 + @pre The source has not been suspended (its `await_suspend`
  266 + has not enqueued it).
  267 +
259   @param o The awaiter to move from. 268   @param o The awaiter to move from.
260   */ 269   */
HITCBC 261   100047 lock_awaiter(lock_awaiter&& o) noexcept 270   100047 lock_awaiter(lock_awaiter&& o) noexcept
HITCBC 262   200094 : m_(o.m_) 271   200094 : m_(o.m_)
HITCBC 263   100047 , cont_(o.cont_) 272   100047 , cont_(o.cont_)
HITCBC 264   100047 , ex_(o.ex_) 273   100047 , ex_(o.ex_)
HITCBC 265   100047 , claimed_(o.claimed_.load( 274   100047 , claimed_(o.claimed_.load(
266   std::memory_order_relaxed)) 275   std::memory_order_relaxed))
HITCBC 267   100047 , canceled_(o.canceled_) 276   100047 , canceled_(o.canceled_)
HITCBC 268   100047 , active_(std::exchange(o.active_, false)) 277   100047 , active_(std::exchange(o.active_, false))
HITCBC 269   100047 , granted_(std::exchange(o.granted_, false)) 278   100047 , granted_(std::exchange(o.granted_, false))
HITCBC 270   200094 , in_list_(std::exchange(o.in_list_, false)) 279   200094 , in_list_(std::exchange(o.in_list_, false))
271   { 280   {
HITCBC 272   100047 } 281   100047 }
273   282  
274 - /** Copy construction is disabled; a waiter is linked into the 283 + /** Deleted: a waiter is linked into the mutex's queue by address.
275 - mutex's wait queue by address.  
276   284  
277   @param other The awaiter that would be copied. 285   @param other The awaiter that would be copied.
278   */ 286   */
279   lock_awaiter(lock_awaiter const& other) = delete; 287   lock_awaiter(lock_awaiter const& other) = delete;
280   288  
281 - /** Copy assignment is disabled; a waiter is linked into the 289 + /** Deleted: a waiter is linked into the mutex's queue by address.
282 - mutex's wait queue by address.  
283   290  
284   @param other The awaiter that would be assigned from. 291   @param other The awaiter that would be assigned from.
285   292  
286   @return A reference to `*this`. 293   @return A reference to `*this`.
287   */ 294   */
288   lock_awaiter& operator=(lock_awaiter const& other) = delete; 295   lock_awaiter& operator=(lock_awaiter const& other) = delete;
289   296  
290 - /** Move assignment is disabled; a waiter is linked into the 297 + /** Deleted: a waiter is linked into the mutex's queue by address.
291 - mutex's wait queue by address.  
292   298  
293   @param other The awaiter that would be moved from. 299   @param other The awaiter that would be moved from.
294   300  
295   @return A reference to `*this`. 301   @return A reference to `*this`.
296   */ 302   */
297   lock_awaiter& operator=(lock_awaiter&& other) = delete; 303   lock_awaiter& operator=(lock_awaiter&& other) = delete;
298   304  
299   /** Acquire the mutex if it is free, reporting whether to suspend. 305   /** Acquire the mutex if it is free, reporting whether to suspend.
300   306  
301   This is not a pure query: on the fast path it takes the lock. 307   This is not a pure query: on the fast path it takes the lock.
302   When the mutex is unlocked, it marks the mutex locked and 308   When the mutex is unlocked, it marks the mutex locked and
303   reports that no suspension is needed. The stop token is not 309   reports that no suspension is needed. The stop token is not
304   consulted, so an uncontended `lock()` succeeds even when stop 310   consulted, so an uncontended `lock()` succeeds even when stop
305 - has already been requested. 311 + has already been requested. On `false` the coroutine suspends.
306   312  
307 - @return `true` if the mutex was free and is now held by the 313 + @return `true` if the mutex was free and is now held; else `false`.
308 - awaiting coroutine. `false` if the mutex is held elsewhere, in  
309 - which case the coroutine suspends.  
310   */ 314   */
HITCBC 311   100052 bool await_ready() const noexcept 315   100052 bool await_ready() const noexcept
312   { 316   {
HITCBC 313   100052 if(!m_->locked_) 317   100052 if(!m_->locked_)
314   { 318   {
HITCBC 315   24 m_->locked_ = true; 319   24 m_->locked_ = true;
HITCBC 316   24 return true; 320   24 return true;
317   } 321   }
HITCBC 318   100028 return false; 322   100028 return false;
319   } 323   }
320   324  
321   /** Enqueue the awaiting coroutine until the mutex is released. 325   /** Enqueue the awaiting coroutine until the mutex is released.
322   326  
323   This is the @ref ContextAwaitable overload of `await_suspend`. 327   This is the @ref ContextAwaitable overload of `await_suspend`.
324   328  
325   If a stop request is already pending on `env->stop_token`, the 329   If a stop request is already pending on `env->stop_token`, the
326   awaiter records the cancellation and does not enqueue. The 330   awaiter records the cancellation and does not enqueue. The
327   mutex is not acquired. 331   mutex is not acquired.
328   332  
329   Otherwise it stores `h` and `env->executor`, links itself into 333   Otherwise it stores `h` and `env->executor`, links itself into
330   the back of the mutex's wait queue, and registers a stop 334   the back of the mutex's wait queue, and registers a stop
331 - callback on `env->stop_token`. Whichever of `unlock()` and that 335 + callback on `env->stop_token`. Whichever of `unlock()`, that
332 - callback claims the awaiter first posts `h` through the stored 336 + callback, and the mutex's destructor claims the awaiter first
333 - executor; the other skips it. 337 + posts `h` through the stored executor. The others skip it.
334   338  
335   @param h The awaiting coroutine, resumed when the mutex is 339   @param h The awaiting coroutine, resumed when the mutex is
336   acquired or the wait is canceled. 340   acquired or the wait is canceled.
337   341  
338   @param env The execution environment. Its executor posts the 342   @param env The execution environment. Its executor posts the
339   resumption and its stop token is watched for the duration of 343   resumption and its stop token is watched for the duration of
340   the wait. It must outlive the wait. 344   the wait. It must outlive the wait.
341   345  
342 - @return `h` if a stop request was already pending, which 346 + A returned `h` resumes the awaiting coroutine at once without
343 - resumes the awaiting coroutine immediately without enqueuing 347 + enqueuing it. A returned `std::noop_coroutine()` leaves the
344 - it. Otherwise `std::noop_coroutine()`, which leaves the  
345   coroutine suspended and returns control to the resumer. 348   coroutine suspended and returns control to the resumer.
  349 +
  350 + @return `h` if stop was already requested, else `noop_coroutine()`.
346   */ 351   */
347   std::coroutine_handle<> 352   std::coroutine_handle<>
HITCBC 348   100028 await_suspend( 353   100028 await_suspend(
349   std::coroutine_handle<> h, 354   std::coroutine_handle<> h,
350   await_context const* env) noexcept 355   await_context const* env) noexcept
351   { 356   {
HITCBC 352   100028 if(env->stop_token.stop_requested()) 357   100028 if(env->stop_token.stop_requested())
353   { 358   {
HITCBC 354   2 canceled_ = true; 359   2 canceled_ = true;
HITCBC 355   2 return h; 360   2 return h;
356   } 361   }
HITCBC 357   100026 cont_.h = h; 362   100026 cont_.h = h;
HITCBC 358   100026 cont_.owner = env->owner; 363   100026 cont_.owner = env->owner;
HITCBC 359   100026 ex_ = env->executor; 364   100026 ex_ = env->executor;
HITCBC 360   100026 m_->waiters_.push_back(this); 365   100026 m_->waiters_.push_back(this);
HITCBC 361   100026 in_list_ = true; 366   100026 in_list_ = true;
HITCBC 362   300078 ::new(stop_cb_buf_) stop_cb_t( 367   300078 ::new(stop_cb_buf_) stop_cb_t(
HITCBC 363   100026 env->stop_token, cancel_fn{this}); 368   100026 env->stop_token, cancel_fn{this});
HITCBC 364   100026 active_ = true; 369   100026 active_ = true;
HITCBC 365   100026 return std::noop_coroutine(); 370   100026 return std::noop_coroutine();
366   } 371   }
367   372  
368   /** Complete the acquisition and report the outcome. 373   /** Complete the acquisition and report the outcome.
369   374  
370   Destroys the stop callback if one is registered, and unlinks a 375   Destroys the stop callback if one is registered, and unlinks a
371 - canceled awaiter from the wait queue. 376 + canceled awaiter from the wait queue. An `error::canceled`
  377 + result means the stop token won the race or the mutex was
  378 + destroyed. The mutex is then not held.
372   379  
373 - @return An empty `results<>` if the mutex is now held by the 380 + @return Empty if the lock is now held, else `error::canceled`.
374 - awaiting coroutine. Otherwise one holding `error::canceled`,  
375 - which means the stop token won the race or the mutex was  
376 - destroyed, and the mutex is not held.  
377   */ 381   */
HITCBC 378   38 [[nodiscard]] results<> await_resume() noexcept 382   38 [[nodiscard]] results<> await_resume() noexcept
379   { 383   {
HITCBC 380   38 if(std::exchange(granted_, false)) 384   38 if(std::exchange(granted_, false))
HITCBC 381   9 m_->granted_to_ = nullptr; 385   9 m_->granted_to_ = nullptr;
HITCBC 382   38 if(active_) 386   38 if(active_)
383   { 387   {
HITCBC 384   17 stop_cb_().~stop_cb_t(); 388   17 stop_cb_().~stop_cb_t();
HITCBC 385   17 if(canceled_) 389   17 if(canceled_)
386   { 390   {
HITCBC 387   8 if(in_list_) 391   8 if(in_list_)
388   { 392   {
HITCBC 389   6 m_->waiters_.remove(this); 393   6 m_->waiters_.remove(this);
HITCBC 390   6 in_list_ = false; 394   6 in_list_ = false;
391   } 395   }
HITCBC 392   8 active_ = false; 396   8 active_ = false;
HITCBC 393   16 return {make_error_code( 397   16 return {make_error_code(
HITCBC 394   8 error::canceled)}; 398   8 error::canceled)};
395   } 399   }
HITCBC 396   9 active_ = false; 400   9 active_ = false;
397   } 401   }
HITCBC 398   30 if(canceled_) 402   30 if(canceled_)
HITCBC 399   4 return {make_error_code( 403   4 return {make_error_code(
HITCBC 400   2 error::canceled)}; 404   2 error::canceled)};
HITCBC 401   28 return {{}}; 405   28 return {{}};
402   } 406   }
403   }; 407   };
404   408  
405   /** Unlocks the mutex automatically when destroyed. 409   /** Unlocks the mutex automatically when destroyed.
406   */ 410   */
407   class [[nodiscard]] lock_guard 411   class [[nodiscard]] lock_guard
408   { 412   {
409   async_mutex* m_; 413   async_mutex* m_;
410   414  
411   public: 415   public:
412 - /// Unlock the mutex, if this guard holds one. 416 + /// Destroy the guard, unlocking the mutex if it holds one.
HITCBC 413   11 ~lock_guard() 417   11 ~lock_guard()
414   { 418   {
HITCBC 415   11 if(m_) 419   11 if(m_)
HITCBC 416   3 m_->unlock(); 420   3 m_->unlock();
HITCBC 417   11 } 421   11 }
418   422  
419   /// Construct a guard that holds no mutex. 423   /// Construct a guard that holds no mutex.
HITCBC 420   2 lock_guard() noexcept 424   2 lock_guard() noexcept
HITCBC 421   2 : m_(nullptr) 425   2 : m_(nullptr)
422   { 426   {
HITCBC 423   2 } 427   2 }
424   428  
425   /** Construct a guard that releases the given mutex on destruction. 429   /** Construct a guard that releases the given mutex on destruction.
426   430  
427   Adopts an already-held lock; it does not acquire one. 431   Adopts an already-held lock; it does not acquire one.
428   432  
429   @param m The mutex to unlock on destruction. It must outlive 433   @param m The mutex to unlock on destruction. It must outlive
430   the guard. 434   the guard.
431   */ 435   */
HITCBC 432   3 explicit lock_guard(async_mutex* m) noexcept 436   3 explicit lock_guard(async_mutex* m) noexcept
HITCBC 433   3 : m_(m) 437   3 : m_(m)
434   { 438   {
HITCBC 435   3 } 439   3 }
436   440  
437   /** Construct by moving, transferring the lock. 441   /** Construct by moving, transferring the lock.
438   442  
439   @par Postconditions 443   @par Postconditions
440   `o` holds no mutex, and its destructor unlocks nothing. 444   `o` holds no mutex, and its destructor unlocks nothing.
441   445  
442   @param o The guard to move from. 446   @param o The guard to move from.
443   */ 447   */
HITCBC 444   6 lock_guard(lock_guard&& o) noexcept 448   6 lock_guard(lock_guard&& o) noexcept
HITCBC 445   6 : m_(std::exchange(o.m_, nullptr)) 449   6 : m_(std::exchange(o.m_, nullptr))
446   { 450   {
HITCBC 447   6 } 451   6 }
448   452  
449   /** Assign by moving, transferring the lock. 453   /** Assign by moving, transferring the lock.
450   454  
451   If this guard already holds a mutex, that mutex is unlocked 455   If this guard already holds a mutex, that mutex is unlocked
452   first. Self-assignment is a no-op. 456   first. Self-assignment is a no-op.
453   457  
454   @par Postconditions 458   @par Postconditions
455   `o` holds no mutex, and its destructor unlocks nothing. 459   `o` holds no mutex, and its destructor unlocks nothing.
456   460  
457   @param o The guard to move from. 461   @param o The guard to move from.
458   462  
459   @return A reference to `*this`. 463   @return A reference to `*this`.
460   */ 464   */
461   lock_guard& operator=(lock_guard&& o) noexcept 465   lock_guard& operator=(lock_guard&& o) noexcept
462   { 466   {
463   if(this != &o) 467   if(this != &o)
464   { 468   {
465   if(m_) 469   if(m_)
466   m_->unlock(); 470   m_->unlock();
467   m_ = std::exchange(o.m_, nullptr); 471   m_ = std::exchange(o.m_, nullptr);
468   } 472   }
469   return *this; 473   return *this;
470   } 474   }
471   475  
472 - /** Copy construction is disabled; a guard uniquely owns the lock. 476 + /** Deleted: a guard uniquely owns the lock.
473   477  
474   @param other The guard that would be copied. 478   @param other The guard that would be copied.
475   */ 479   */
476   lock_guard(lock_guard const& other) = delete; 480   lock_guard(lock_guard const& other) = delete;
477   481  
478 - /** Copy assignment is disabled; a guard uniquely owns the lock. 482 + /** Deleted: a guard uniquely owns the lock.
479   483  
480   @param other The guard that would be assigned from. 484   @param other The guard that would be assigned from.
481   485  
482   @return A reference to `*this`. 486   @return A reference to `*this`.
483   */ 487   */
484   lock_guard& operator=(lock_guard const& other) = delete; 488   lock_guard& operator=(lock_guard const& other) = delete;
485   }; 489   };
486   490  
487   /** Acquires the mutex like `lock_awaiter`, then resumes with a `lock_guard` that unlocks it. 491   /** Acquires the mutex like `lock_awaiter`, then resumes with a `lock_guard` that unlocks it.
488   */ 492   */
489   class lock_guard_awaiter 493   class lock_guard_awaiter
490   { 494   {
491   async_mutex* m_; 495   async_mutex* m_;
492   lock_awaiter inner_; 496   lock_awaiter inner_;
493   497  
494   public: 498   public:
495   /** Construct an awaiter for the given mutex. 499   /** Construct an awaiter for the given mutex.
496   500  
497 - @param m The mutex to acquire. It must outlive the awaiter. 501 + @param m The mutex to acquire. It must outlive the awaiter,
  502 + unless the mutex's destructor runs while the awaiter is
  503 + suspended. The destructor then cancels the awaiter.
498   */ 504   */
HITCBC 499   5 explicit lock_guard_awaiter(async_mutex* m) noexcept 505   5 explicit lock_guard_awaiter(async_mutex* m) noexcept
HITCBC 500   5 : m_(m) 506   5 : m_(m)
HITCBC 501   5 , inner_(m) 507   5 , inner_(m)
502   { 508   {
HITCBC 503   5 } 509   5 }
504   510  
505   /** Acquire the mutex if it is free, reporting whether to suspend. 511   /** Acquire the mutex if it is free, reporting whether to suspend.
506   512  
507   Delegates to @ref lock_awaiter::await_ready, so as there this is 513   Delegates to @ref lock_awaiter::await_ready, so as there this is
508 - not a pure query: on the fast path it takes the lock. 514 + not a pure query: on the fast path it takes the lock. On
  515 + `false` the coroutine suspends.
509   516  
510 - @return `true` if the mutex was free and is now held by the 517 + @return `true` if the mutex was free and is now held; else `false`.
511 - awaiting coroutine. `false` if the mutex is held elsewhere, in  
512 - which case the coroutine suspends.  
513   */ 518   */
HITCBC 514   5 bool await_ready() const noexcept 519   5 bool await_ready() const noexcept
515   { 520   {
HITCBC 516   5 return inner_.await_ready(); 521   5 return inner_.await_ready();
517   } 522   }
518   523  
519   /** Enqueue the awaiting coroutine until the mutex is released. 524   /** Enqueue the awaiting coroutine until the mutex is released.
520   525  
521   This is the @ref ContextAwaitable overload of `await_suspend`. It 526   This is the @ref ContextAwaitable overload of `await_suspend`. It
522   delegates to @ref lock_awaiter::await_suspend on the wrapped 527   delegates to @ref lock_awaiter::await_suspend on the wrapped
523   awaiter, so it has that function's contract. 528   awaiter, so it has that function's contract.
524   529  
525   @param h The awaiting coroutine, resumed when the mutex is 530   @param h The awaiting coroutine, resumed when the mutex is
526   acquired or the wait is canceled. 531   acquired or the wait is canceled.
527   532  
528   @param env The execution environment. Its executor posts the 533   @param env The execution environment. Its executor posts the
529   resumption and its stop token is watched for the duration of 534   resumption and its stop token is watched for the duration of
530   the wait. It must outlive the wait. 535   the wait. It must outlive the wait.
531   536  
532 - @return `h` if a stop request was already pending, which 537 + A returned `h` resumes the awaiting coroutine at once without
533 - resumes the awaiting coroutine immediately without enqueuing 538 + enqueuing it. A returned `std::noop_coroutine()` leaves the
534 - it. Otherwise `std::noop_coroutine()`, which leaves the  
535   coroutine suspended and returns control to the resumer. 539   coroutine suspended and returns control to the resumer.
  540 +
  541 + @return `h` if stop was already requested, else `noop_coroutine()`.
536   */ 542   */
537   std::coroutine_handle<> 543   std::coroutine_handle<>
HITCBC 538   2 await_suspend( 544   2 await_suspend(
539   std::coroutine_handle<> h, 545   std::coroutine_handle<> h,
540   await_context const* env) noexcept 546   await_context const* env) noexcept
541   { 547   {
HITCBC 542   2 return inner_.await_suspend(h, env); 548   2 return inner_.await_suspend(h, env);
543   } 549   }
544   550  
545   /** Complete the acquisition and report the outcome. 551   /** Complete the acquisition and report the outcome.
546   552  
547 - @return A `results<lock_guard>` destructuring as 553 + The result destructures as `[ec, guard]`. On success `ec` is
548 - `[ec, guard]`. On success `ec` is empty and `guard` holds the 554 + empty and `guard` holds the mutex, releasing it when destroyed.
549 - mutex, releasing it when destroyed. If the wait was canceled, 555 + If the wait was canceled, `ec` is `error::canceled` and `guard`
550 - `ec` is `error::canceled` and `guard` holds no mutex. 556 + holds no mutex.
  557 +
  558 + @return A `results<lock_guard>` holding the outcome and guard.
551   */ 559   */
HITCBC 552   5 [[nodiscard]] results<lock_guard> await_resume() noexcept 560   5 [[nodiscard]] results<lock_guard> await_resume() noexcept
553   { 561   {
HITCBC 554   5 auto r = inner_.await_resume(); 562   5 auto r = inner_.await_resume();
HITCBC 555   5 if(std::get<0>(r)) 563   5 if(std::get<0>(r))
HITCBC 556   2 return {std::get<0>(r), lock_guard()}; 564   2 return {std::get<0>(r), lock_guard()};
HITCBC 557   3 return {std::error_code(), lock_guard(m_)}; 565   3 return {std::error_code(), lock_guard(m_)};
558   } 566   }
559   }; 567   };
560   568  
561   /// Construct an unlocked mutex. 569   /// Construct an unlocked mutex.
HITCBC 562   3 async_mutex() = default; 570   3 async_mutex() = default;
563   571  
564   /** Destroy the mutex, canceling every coroutine still waiting. 572   /** Destroy the mutex, canceling every coroutine still waiting.
565   573  
566   Each waiter is posted to its executor to resume with 574   Each waiter is posted to its executor to resume with
567   `error::canceled`, as if its stop token had been triggered. An 575   `error::canceled`, as if its stop token had been triggered. An
568   executor that can no longer run it abandons it instead, possibly 576   executor that can no longer run it abandons it instead, possibly
569   before this destructor returns. Either way the waiter no longer 577   before this destructor returns. Either way the waiter no longer
570   refers to the mutex. 578   refers to the mutex.
571   579  
572   A waiter handed the lock but not yet resumed resumes with 580   A waiter handed the lock but not yet resumed resumes with
573   `error::canceled` instead, holding nothing. 581   `error::canceled` instead, holding nothing.
574   582  
575 - @pre No coroutine holds the lock. 583 + @pre No coroutine holds the lock, other than a waiter handed it
  584 + but not yet resumed.
576   */ 585   */
HITCBC 577   24 ~async_mutex() 586   24 ~async_mutex()
578   { 587   {
HITCBC 579   24 if(unlocking_) 588   24 if(unlocking_)
HITCBC 580   1 unlocking_->gone = true; 589   1 unlocking_->gone = true;
581   // Already posted, so it is only told the lock no longer exists. 590   // Already posted, so it is only told the lock no longer exists.
HITCBC 582   24 if(granted_to_) 591   24 if(granted_to_)
583   { 592   {
HITCBC 584   1 granted_to_->granted_ = false; 593   1 granted_to_->granted_ = false;
HITCBC 585   1 granted_to_->canceled_ = true; 594   1 granted_to_->canceled_ = true;
586   } 595   }
HITCBC 587   28 while(auto* w = waiters_.pop_front()) 596   28 while(auto* w = waiters_.pop_front())
588   { 597   {
HITCBC 589   4 w->in_list_ = false; 598   4 w->in_list_ = false;
HITCBC 590   4 if(!w->claimed_.exchange(true, std::memory_order_acq_rel)) 599   4 if(!w->claimed_.exchange(true, std::memory_order_acq_rel))
591   { 600   {
HITCBC 592   3 w->canceled_ = true; 601   3 w->canceled_ = true;
HITCBC 593   3 w->ex_.post(w->cont_); 602   3 w->ex_.post(w->cont_);
594   } 603   }
HITCBC 595   4 } 604   4 }
HITCBC 596   24 } 605   24 }
597   606  
598 - /** Copy construction is disabled; suspended waiters point into the 607 + /** Deleted: suspended waiters point into the mutex's wait queue.
599 - mutex's wait queue.  
600   608  
601   @param other The mutex that would be copied. 609   @param other The mutex that would be copied.
602   */ 610   */
603   async_mutex(async_mutex const& other) = delete; 611   async_mutex(async_mutex const& other) = delete;
604   612  
605 - /** Copy assignment is disabled; suspended waiters point into the 613 + /** Deleted: suspended waiters point into the mutex's wait queue.
606 - mutex's wait queue.  
607   614  
608   @param other The mutex that would be assigned from. 615   @param other The mutex that would be assigned from.
609   616  
610   @return A reference to `*this`. 617   @return A reference to `*this`.
611   */ 618   */
612   async_mutex& operator=(async_mutex const& other) = delete; 619   async_mutex& operator=(async_mutex const& other) = delete;
613   620  
614 - /** Move construction is disabled; suspended waiters point into the 621 + /** Deleted: suspended waiters point into the mutex's wait queue.
615 - mutex's wait queue.  
616   622  
617   @param other The mutex that would be moved from. 623   @param other The mutex that would be moved from.
618   */ 624   */
619   async_mutex(async_mutex&& other) = delete; 625   async_mutex(async_mutex&& other) = delete;
620   626  
621 - /** Move assignment is disabled; suspended waiters point into the 627 + /** Deleted: suspended waiters point into the mutex's wait queue.
622 - mutex's wait queue.  
623   628  
624   @param other The mutex that would be moved from. 629   @param other The mutex that would be moved from.
625   630  
626   @return A reference to `*this`. 631   @return A reference to `*this`.
627   */ 632   */
628   async_mutex& operator=(async_mutex&& other) = delete; 633   async_mutex& operator=(async_mutex&& other) = delete;
629   634  
630 - /** Returns an awaiter that acquires the mutex. 635 + /** Return an awaiter that acquires the mutex.
631   636  
632   @return An awaitable that await-returns `(error_code)`. 637   @return An awaitable that await-returns `(error_code)`.
633   */ 638   */
HITCBC 634   100047 lock_awaiter lock() noexcept 639   100047 lock_awaiter lock() noexcept
635   { 640   {
HITCBC 636   100047 return lock_awaiter{this}; 641   100047 return lock_awaiter{this};
637   } 642   }
638   643  
639 - /** Returns an awaiter that acquires the mutex with RAII. 644 + /** Return an awaiter that acquires the mutex with RAII.
640   645  
641   @return An awaitable that await-returns `(error_code,lock_guard)`. 646   @return An awaitable that await-returns `(error_code,lock_guard)`.
642   */ 647   */
HITCBC 643   5 lock_guard_awaiter scoped_lock() noexcept 648   5 lock_guard_awaiter scoped_lock() noexcept
644   { 649   {
HITCBC 645   5 return lock_guard_awaiter(this); 650   5 return lock_guard_awaiter(this);
646   } 651   }
647   652  
648 - /** Releases the mutex. 653 + /** Release the mutex.
649   654  
650   If waiters are queued, the next eligible waiter is 655   If waiters are queued, the next eligible waiter is
651   resumed with the lock held. Canceled waiters are 656   resumed with the lock held. Canceled waiters are
652   skipped. If no eligible waiter remains, the mutex 657   skipped. If no eligible waiter remains, the mutex
653   becomes unlocked. 658   becomes unlocked.
  659 +
  660 + @pre The calling coroutine holds the lock.
654   */ 661   */
HITCBC 655   100032 void unlock() noexcept 662   100032 void unlock() noexcept
656   { 663   {
HITCBC 657   100032 if(unlocking_) 664   100032 if(unlocking_)
658   { 665   {
659   // Reached from a granted waiter destroyed by the post below; 666   // Reached from a granted waiter destroyed by the post below;
660   // that call hands the lock on once the post returns. 667   // that call hands the lock on once the post returns.
HITCBC 661   100002 unlocking_->again = true; 668   100002 unlocking_->again = true;
HITCBC 662   100003 return; 669   100003 return;
663   } 670   }
HITCBC 664   30 unlock_scope scope; 671   30 unlock_scope scope;
HITCBC 665   30 unlocking_ = &scope; 672   30 unlocking_ = &scope;
666   do 673   do
667   { 674   {
HITCBC 668   100031 scope.again = false; 675   100031 scope.again = false;
HITCBC 669   100031 auto* waiter = grant_next(); 676   100031 auto* waiter = grant_next();
HITCBC 670   100031 if(!waiter) 677   100031 if(!waiter)
HITCBC 671   19 break; 678   19 break;
HITCBC 672   100012 waiter->ex_.post(waiter->cont_); 679   100012 waiter->ex_.post(waiter->cont_);
HITCBC 673   100012 if(scope.gone) 680   100012 if(scope.gone)
HITCBC 674   1 return; 681   1 return;
675   } 682   }
HITCBC 676   100011 while(scope.again); 683   100011 while(scope.again);
HITCBC 677   29 unlocking_ = nullptr; 684   29 unlocking_ = nullptr;
678   } 685   }
679   686  
680   private: 687   private:
681   // Hand the lock to the next unclaimed waiter, or release it. 688   // Hand the lock to the next unclaimed waiter, or release it.
HITCBC 682   100031 lock_awaiter* grant_next() noexcept 689   100031 lock_awaiter* grant_next() noexcept
683   { 690   {
HITCBC 684   100032 while(auto* waiter = waiters_.pop_front()) 691   100032 while(auto* waiter = waiters_.pop_front())
685   { 692   {
HITCBC 686   100013 waiter->in_list_ = false; 693   100013 waiter->in_list_ = false;
HITCBC 687   100013 if(!waiter->claimed_.exchange( 694   100013 if(!waiter->claimed_.exchange(
688   true, std::memory_order_acq_rel)) 695   true, std::memory_order_acq_rel))
689   { 696   {
HITCBC 690   100012 waiter->granted_ = true; 697   100012 waiter->granted_ = true;
HITCBC 691   100012 granted_to_ = waiter; 698   100012 granted_to_ = waiter;
HITCBC 692   100012 return waiter; 699   100012 return waiter;
693   } 700   }
HITCBC 694   1 } 701   1 }
HITCBC 695   19 locked_ = false; 702   19 locked_ = false;
HITCBC 696   19 return nullptr; 703   19 return nullptr;
697   } 704   }
698   705  
699   public: 706   public:
700 - /** Returns true if the mutex is currently locked. 707 + /** Check whether the mutex is currently locked.
701   708  
702   @return `true` if the mutex is held; otherwise `false`. 709   @return `true` if the mutex is held; otherwise `false`.
703   */ 710   */
HITCBC 704   29 bool is_locked() const noexcept 711   29 bool is_locked() const noexcept
705   { 712   {
HITCBC 706   29 return locked_; 713   29 return locked_;
707   } 714   }
708   }; 715   };
709   716  
710   } // namespace capy 717   } // namespace capy
711   } // namespace boost 718   } // namespace boost
712   719  
713   #endif 720   #endif