Async Mutex

Fair FIFO coroutine locking with async_mutex.

What This Example Shows

  • Using async_mutex for mutual exclusion between coroutines

  • RAII lock guards with scoped_lock

  • Running async_mutex on a strand, as its threading model requires

  • Comparing async_mutex to strand-based serialization

Source Code

#include <boost/capy.hpp>
#include <iostream>
#include <latch>
#include <vector>

namespace capy = boost::capy;

int main()
{
    capy::thread_pool pool;
    capy::strand s{pool.get_executor()};
    std::latch done(1);

    auto on_complete = [&done](auto&&...) { done.count_down(); };
    auto on_error = [&done](std::exception_ptr ep) {
        try { std::rethrow_exception(ep); }
        catch (std::exception const& e) {
            std::cerr << "Error: " << e.what() << "\n";
        }
        catch (...) {
            std::cerr << "Error: unknown exception\n";
        }
        done.count_down();
    };

    capy::async_mutex mtx;
    int acquisition_order = 0;
    std::vector<int> order_log;

    auto worker = [&](int id) -> capy::task<capy::results<>> {
        std::cout << "Worker " << id << " waiting for lock\n";
        auto [ec, guard] = co_await mtx.scoped_lock();
        if (ec)
        {
            std::cout << "Worker " << id
                      << " canceled: " << ec.message() << "\n";
            co_return capy::results<>{ec};
        }

        int seq = acquisition_order++;
        order_log.push_back(id);
        std::cout << "Worker " << id
                  << " acquired lock (sequence " << seq << ")\n";

        std::cout << "Worker " << id << " releasing lock\n";
        co_return capy::results<>{};
    };

    auto run_all = [&]() -> capy::task<> {
        auto r = co_await capy::when_all(
            worker(0), worker(1), worker(2),
            worker(3), worker(4), worker(5));
        if(std::get<0>(r))
            std::cerr << "when_all error: "
                      << std::get<0>(r).message() << "\n";
    };

    // Run on a strand so async_mutex operations are single-threaded
    capy::run_async(s, on_complete, on_error)(run_all());
    done.wait();

    std::cout << "\nAcquisition order: ";
    for (std::size_t i = 0; i < order_log.size(); ++i)
    {
        if (i > 0)
            std::cout << " -> ";
        std::cout << "W" << order_log[i];
    }
    std::cout << "\n";

    return 0;
}

Build

add_executable(capy_example_async_mutex async_mutex.cpp)
target_link_libraries(capy_example_async_mutex PRIVATE Boost::capy)

Walkthrough

Creating the Mutex

capy::async_mutex mtx;

async_mutex is a coroutine-aware mutex. Unlike std::mutex, it suspends the calling coroutine instead of blocking the thread, allowing other coroutines to run while waiting for the lock.

The mutex is designed for use on one executor. The example runs every worker on a strand, so no two workers touch the mutex at the same time.

Scoped Lock

auto [ec, guard] = co_await mtx.scoped_lock();
if (ec)
{
    std::cout << "Worker " << id
              << " canceled: " << ec.message() << "\n";
    co_return capy::results<>{ec};
}

scoped_lock() returns a results with an error code and an RAII guard. The guard automatically releases the lock when it goes out of scope. If the operation is canceled (e.g., via a stop token), ec is set.

FIFO Fairness

Unlike std::mutex, which has no fairness guarantees, async_mutex queues waiting coroutines in FIFO order. The first coroutine to suspend in scoped_lock() is the first to acquire the lock.

No worker in this program suspends while it holds the lock. Each worker finds the mutex free and takes it at once, so no worker ever waits in the queue. The output order is the order in which the strand runs the workers.

Strand vs Async Mutex

The strand serialization example showed how a strand can protect shared state by running all coroutines sequentially. async_mutex serializes only the critical section. Outside it, coroutines interleave at each suspension point, and a coroutine can hold the lock across a co_await. The coroutines still share one executor or strand.

Output

Worker 0 waiting for lock
Worker 0 acquired lock (sequence 0)
Worker 0 releasing lock
Worker 1 waiting for lock
Worker 1 acquired lock (sequence 1)
Worker 1 releasing lock
Worker 2 waiting for lock
Worker 2 acquired lock (sequence 2)
Worker 2 releasing lock
Worker 3 waiting for lock
Worker 3 acquired lock (sequence 3)
Worker 3 releasing lock
Worker 4 waiting for lock
Worker 4 acquired lock (sequence 4)
Worker 4 releasing lock
Worker 5 waiting for lock
Worker 5 acquired lock (sequence 5)
Worker 5 releasing lock

Acquisition order: W0 -> W1 -> W2 -> W3 -> W4 -> W5

Exercises

  1. Inside the critical section, co_await an async_event that another task sets later. The other workers then queue on the mutex, and they acquire it in FIFO order

  2. Use a stop token to cancel waiting workers after a timeout

  3. Replace async_mutex with a strand and compare the two approaches

Next Steps