Skip to content

How does one event reach every subscriber?

Level: 201 · anyone who wants many readers of one stream

Stub — a question and its expected answers, not yet a lesson. No program behind this page has been written or run, so nothing on it has been through the check that backs every finished page. The table is what the finished lesson is expected to find, and every cell is unverified until a program prints it. (Not machine-checked here.)

One line: A channel delivers each value to one receiver, so a value that several threads must all see needs a different shape — a broadcast — where each subscriber has its own queue and a slow subscriber either delays the publisher, is dropped behind, or loses messages, and the choice among those three is the whole design.

The question

A price update must reach every one of five display threads. Put it on one channel and one display gets it. The page builds the broadcast: the publisher writes to five queues, one per subscriber. Then it slows one subscriber to a crawl and shows what happens to the other four — and to the publisher — under each of the three policies.

What each language is expected to say

Expected answer, to be verified by the program
Rust five mpsc senders, one per subscriber; tokio::sync::broadcast implements the lagging-receiver policy (link, not run)
Go five channels, or one sync.Cond.Broadcast with each subscriber holding the latest value
C five pipes, or a shared ring buffer with a per-reader cursor
C++ five hand-built queues; or one std::condition_variable::notify_all with a sequence number
Java five BlockingQueues; SubmissionPublisher from java.util.concurrent.Flow is the standard broadcast with backpressure
Python five Queues; or asyncio.Condition.notify_all

What the programs have to show

  • one message, five subscribers: five receipts
  • one slow subscriber: under a bounded queue the publisher stalls, under drop-oldest it loses the counted number, under unbounded its queue grows
  • the Java Flow version with its request-N backpressure

See also