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.

Cancellation only applies while the coroutine is suspended in the wait queue. If the mutex is unlocked when lock() is called, the lock is acquired immediately even if the stop token is already signaled.

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

async_mutex cm;

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

// Or with RAII:
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

operator= [deleted]

Assignment operators

is_locked

Returns true if the mutex is currently locked.

lock

Returns an awaiter that acquires the mutex.

scoped_lock

Returns an awaiter that acquires the mutex with RAII.

unlock

Releases the mutex.

Created with MrDocs