Boost C++ Libraries

PrevUpHomeNext

Class template async_channel

boost::taar::async_channel — A thread-safe, executor-agnostic multi-producer FIFO of values with asynchronous receive.

Synopsis

// In header: <boost/taar/core/async_channel.hpp>

template<typename T> 
class async_channel {
public:

  // public member functions
  async_channel() = default;
  async_channel(async_channel const &) = delete;
  async_channel & operator=(async_channel const &) = delete;
  bool push(T);
  std::size_t trim(std::size_t);
  void close();
  bool closed() const;
  std::size_t size() const;
  template<typename CompletionToken> auto async_receive(CompletionToken &&);
};

Description

Producers call push from any thread. Consumers suspend in async_receive until a value is available; each waiter resumes on the executor associated with its own completion handler. Receiving completes with std::nullopt once the channel is closed and drained, or when the waiting operation is cancelled through its cancellation slot. Used by the MCP endpoint to feed server-to-client event streams.

The cancellation handler installed on a consumer's slot refers to the channel through a weak pointer, so a slot that still carries it after the channel is gone emits into nothing. Producers never touch a consumer's slot: only the consumer's own thread assigns it.

async_channel public member functions

  1. async_channel() = default;
  2. async_channel(async_channel const &) = delete;
  3. async_channel & operator=(async_channel const &) = delete;
  4. bool push(T value);
    Enqueue value, or hand it directly to the first waiter. Returns false if closed.
  5. std::size_t trim(std::size_t max);
    Drop the oldest queued values until at most max remain. Returns how many were dropped.
  6. void close();
    Close the channel: pending waiters complete with nullopt, later pushes fail.
  7. bool closed() const;
  8. std::size_t size() const;
  9. template<typename CompletionToken> 
      auto async_receive(CompletionToken && token);
    Receive the next value.

    Completion signature: void(std::optional<T>).

    Values queued before close are still delivered; afterwards nullopt. Cancellation via the completion handler's associated slot also completes with nullopt.


PrevUpHomeNext