boost::capy::async_mutex

An asynchronous mutex for coroutines.

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

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

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() {
    auto [ec, guard] = co_await cm.scoped_lock();
    if(ec)
        co_return;
    // ... critical section ...
    // unlocks automatically
}

Types

Name

Description

lock_awaiter

Awaiter returned by lock().

lock_guard

RAII lock guard for async_mutex.

lock_guard_awaiter

Awaiter returned by scoped_lock() that returns a lock_guard on resume.

Member Functions

Name

Description

async_mutex [constructor]

Constructors

operator= [deleted]

Copy assignment operator

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