Producer-Consumer

Two tasks communicating via an async event, with strand serialization.

What This Example Shows

  • Using async_event for coroutine synchronization

  • Running multiple concurrent tasks with when_all

  • Using strand to serialize access to shared state

  • Task-to-task communication patterns

Source Code

#include <boost/capy.hpp>
#include <boost/capy/ex/strand.hpp>
#include <iostream>
#include <latch>

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) { done.count_down(); };

    capy::async_event data_ready;
    int shared_value = 0;

    auto producer = [&]() -> capy::task<capy::results<>> {
        std::cout << "Producer: preparing data...\n";
        shared_value = 42;
        std::cout << "Producer: data ready, signaling\n";
        data_ready.set();
        co_return capy::results<>{};
    };

    auto consumer = [&]() -> capy::task<capy::results<>> {
        std::cout << "Consumer: waiting for data...\n";
        auto [ec] = co_await data_ready.wait();
        (void)ec;
        std::cout << "Consumer: received value " << shared_value << "\n";
        co_return capy::results<>{};
    };

    // Run both tasks concurrently using when_all, through a strand.
    // The strand serializes execution, ensuring thread-safe access
    // to the shared async_event and shared_value.
    auto run_both = [&]() -> capy::task<> {
        (void) co_await capy::when_all(producer(), consumer());
    };

    capy::run_async(s, on_complete, on_error)(run_both());

    done.wait();  // Block until tasks complete
    return 0;
}

Build

add_executable(capy_example_producer_consumer producer_consumer.cpp)
target_link_libraries(capy_example_producer_consumer PRIVATE Boost::capy)

Walkthrough

The Strand

capy::strand s{pool.get_executor()};

A strand is an executor adaptor that serializes execution. All coroutines dispatched through a strand are guaranteed not to run concurrently, making it safe to access shared state without explicit locking. async_event is not thread-safe.

The Event

capy::async_event data_ready;

async_event is a manual-reset signaling mechanism. One task can set() it; other tasks can wait() for it. When set, all current waiters resume, and the event stays set (later wait() calls return immediately) until clear() is called.

Producer

auto producer = [&]() -> capy::task<capy::results<>> {
    std::cout << "Producer: preparing data...\n";
    shared_value = 42;
    std::cout << "Producer: data ready, signaling\n";
    data_ready.set();
    co_return capy::results<>{};
};

Consumer

auto consumer = [&]() -> capy::task<capy::results<>> {
    std::cout << "Consumer: waiting for data...\n";
    auto [ec] = co_await data_ready.wait();
    (void)ec;
    std::cout << "Consumer: received value " << shared_value << "\n";
    co_return capy::results<>{};
};

In this program the producer runs first and sets the event before the consumer starts. The consumer’s co_await data_ready.wait() finds the event set and does not suspend. If the event were clear, the wait would suspend until set() is called.

Running Both

// Run both tasks concurrently using when_all, through a strand.
// The strand serializes execution, ensuring thread-safe access
// to the shared async_event and shared_value.
auto run_both = [&]() -> capy::task<> {
    (void) co_await capy::when_all(producer(), consumer());
};

capy::run_async(s, on_complete, on_error)(run_both());

when_all runs both tasks concurrently within the same parent coroutine context, but the strand ensures they don’t run at the same time on different threads.

Completion Synchronization

std::latch done(1);

auto on_complete = [&done](auto&&...) { done.count_down(); };
auto on_error = [&done](std::exception_ptr) { done.count_down(); };
// ...
done.wait();  // Block until tasks complete

The std::latch ensures main() waits for the tasks to complete before returning.

Output

Producer: preparing data...
Producer: data ready, signaling
Consumer: waiting for data...
Consumer: received value 42

The output order is the same on every run. The strand runs the two children in argument order, and the producer never suspends, so it finishes before the consumer starts.

Exercises

  1. Add multiple consumers that all wait for the same event

  2. Create a producer that sets the event multiple times (use a loop with a new event each iteration)

  3. Add error handling—what happens if the producer throws?

Next Steps