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