Skip to main content

Module bounded_mpmc

Module bounded_mpmc 

Source
Expand description

Bounded multi-producer, multi-consumer channel with lock-free send and recv.

§Overview

A bounded MPMC channel allows multiple senders and multiple receivers to share a fixed-size ring buffer. Each message is consumed by exactly one receiver (no broadcast). This is ideal for work-stealing patterns, thread pools, and load-balanced message distribution.

§Capacity and send behavior

When the buffer is full:

  • send() returns Err(SendError(msg)) immediately (fail-fast, no blocking)
  • As any receiver pops a message, space opens up for new sends
  • Each send wakes at most one waiting receiver (efficient, prevents thundering herd)

§Lock-free design

  • send() is lock-free: atomic ring buffer push; wakes one receiver via Mutex briefly
  • try_recv() is lock-free: atomic ring buffer pop
  • recv() is lock-free on hot path; uses Mutex only for waiter registration
  • MPMC wake semantics: one send wakes one receiver to reduce contention

§Cloning

  • Both Sender and Receiver are fully cloneable
  • Each clone gets an independent identity tracked via atomic counters
  • Disconnect is only observed when the last sender or receiver is dropped

§Example

let (tx, rx) = bounded_mpmc::channel(10);

// Multiple senders
let tx1 = tx.clone();
std::thread::spawn(move || { tx.send("from tx").ok(); });
std::thread::spawn(move || { tx1.send("from tx1").ok(); });

// Multiple receivers (each message goes to one receiver)
let rx1 = rx.clone();
std::thread::spawn(move || { let msg = rx.recv(); });
std::thread::spawn(move || { let msg = rx1.recv(); });

Structs§

Receiver
Sender

Functions§

after
One-shot Receiver<Instant> that fires once after duration.
channel
Create a lock-free bounded MPMC channel with the given capacity.
never
A Receiver<T> that never yields values and never disconnects.