boost::capy::async_mutex

Queues coroutines in lock() and resumes exactly one when the mutex is free.

Synopsis

class async_mutex;

Description

This mutex provides mutual exclusion for coroutines without blocking. When a coroutine attempts to acquire a locked mutex, it suspends and is added to an intrusive wait queue. When the holder unlocks, the next waiter is resumed with the lock held.

Cancellation

When a coroutine is suspended waiting for the mutex and its stop token is triggered, the waiter completes with error::canceled instead of acquiring the lock.

If the mutex is unlocked, lock() acquires it without consulting the stop token. Otherwise a pending stop request completes the wait with error::canceled. When a stop request races with unlock(), whichever reaches the waiter first decides the result. If the mutex is destroyed before a granted waiter resumes, that waiter completes with error::canceled instead.

Zero Allocation

No heap allocation occurs for lock operations.

Thread Safety

Distinct objects: Safe. Shared objects: Unsafe.

The mutex operations are designed for single‐threaded use on one executor. The stop callback may fire from any thread.

This type is non‐copyable and non‐movable because suspended waiters hold intrusive pointers into the mutex's internal list.

Example

capy::async_mutex cm;

capy::task<> protected_operation() {
    auto [ec] = co_await cm.lock();
    if(ec)
        co_return;
    // ... critical section ...
    cm.unlock();
}

// Or with RAII:
capy::task<> protected_operation_raii() {
    auto [ec, guard] = co_await cm.scoped_lock();
    if(ec)
        co_return;
    // ... critical section ...
    // unlocks automatically
}

Types

Name

Description

lock_awaiter

Suspends the caller until the mutex is free, or resumes it with error::canceled on a stop request.

lock_guard

Unlocks the mutex automatically when destroyed.

lock_guard_awaiter

Acquires the mutex like lock_awaiter, then resumes with a lock_guard that unlocks it.

Member Functions

Name

Description

async_mutex [constructor]

Constructors

~async_mutex [destructor]

Destroy the mutex, canceling every coroutine still waiting.

operator=

Deleted: suspended waiters point into the mutex's wait queue.

is_locked

Check whether the mutex is currently locked.

lock

Return an awaiter that acquires the mutex.

scoped_lock

Return an awaiter that acquires the mutex with RAII.

unlock

Release the mutex.

Created with MrDocs