Coordinating Hydrogen and Oxygen Threads into Complete Water Molecules
System DesignModel answerLast updated
Design a lock-based coordinator that lets exactly two hydrogen threads and one oxygen thread print as one water molecule, with no spinning, no interleaving, and no starvation.
You are given a shared runtime with two entry points:
hydrogen(releaseHydrogen)— invoked by a hydrogen-producing thread; the callback prints/emitsHand must be executed by that same calling thread.oxygen(releaseOxygen)— invoked by an oxygen-producing thread; the callback prints/emitsOon the calling thread.
Hydrogen and oxygen threads arrive in an arbitrary order and an arbitrary (possibly unbalanced) ratio, forever — the stream is unbounded. Design the coordination so that:
- Valid grouping: if you cut the entire output stream into consecutive chunks of three characters, every chunk contains exactly two
Hand oneO(the order inside a chunk is free). - Safety: no atom is emitted unless it belongs to a complete molecule, and the three emissions of one molecule never mix with those of another — molecule k finishes emitting before molecule k+1 starts.
- Liveness: once at least two hydrogens and one oxygen are waiting, a molecule forms; no thread that has arrived waits forever while later arrivals of the same type keep getting served (starvation-freedom).
- No busy-waiting: waiting must block, using semaphores, mutexes, or condition variables — never spin loops.
- Bounded resources: memory should scale with the number of currently waiting threads, not with the length of the stream; atoms that cannot yet be paired simply block.
Deliverable: a precise statement of the invariants, pseudocode (or real code) for hydrogen and oxygen, and a correctness argument covering composition, non-interleaving, progress, and fairness. Discuss the failure modes of a naive design and how the arrival-order/fairness trade-off changes your choice of primitive.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying the contract first
A concurrency question like this is really a design question. Before touching primitives I pin down the interface and the invariants I will be defending.
- Each atom arrives on its own thread and must run its own release callback — I cannot batch the prints on a coordinator thread and pretend that satisfies the interface.
- Composition invariant: counting emissions in triples, each triple is exactly two
Hplus oneO. - Non-interleaving invariant: let molecule k be the k-th bonded set of atoms. All three of k's emissions happen-before any emission of k+1.
- Progress: if the waiting pools hold ≥2 H and ≥1 O, some molecule bonds.
- Fairness: a waiting atom is never overtaken indefinitely by later arrivals of the same type.
- Blocking only, and memory proportional to the number of currently blocked threads. Atoms that can't be paired yet just wait — an unbalanced stream inherently leaves surplus atoms parked, which is correct, not a bug.
Design A: two counters plus a barrier
Three primitives do the work:
hSlots = Semaphore(2)— caps how many hydrogens may be inside the current molecule.oSlots = Semaphore(1)— caps oxygens to one.gate = Barrier(3)— a rendezvous that doesn't open until three atoms have arrived.
hydrogen(release):
hSlots.acquire()
gate.wait() # blocks until two H and one O have all arrived
release() # emit H on this thread
hSlots.release()
oxygen(release):
oSlots.acquire()
gate.wait()
release() # emit O
oSlots.release()
Why composition holds. Between them, the two semaphores admit at most 2 H and 1 O concurrently, and the barrier needs exactly 3 participants; a barrier trip therefore contains exactly 2 H + 1 O.
Why molecules don't interleave. A slot is returned after the emit. The next molecule's barrier cannot trip until it holds two H permits and one O permit, and each permit only reappears after its previous holder has already printed. So molecule k's three prints all precede any print of k+1.
Where it breaks down: fairness. Most semaphores — threading.Semaphore among them — are not FIFO; whichever waiter wins the race gets the permit. A specific H thread can be unlucky forever, so this design is not starvation-free. The fix is either a fair semaphore (Java's new Semaphore(2, true)) or explicit queueing. A related subtlety interviewers like to probe: if you swap the order and release the slot before the emit, you get interleaving between consecutive molecules — the safety proof collapses.
Design B: a monitor with FIFO ticket queues (starvation-free)
To make fairness provable, hold all the state under one mutex/condition variable:
- two FIFO deques of waiting tickets, one for H and one for O;
nextId, the id to hand the next molecule formed;serving, the molecule currently allowed to emit;left, how many ofserving's members still have to emit.
On arrival, append a ticket. If the pools hold ≥2 H and ≥1 O, pop the two oldest H and the oldest O, stamp them with nextId, and bump nextId. Then block while ticket.id is None or ticket.id != serving. The emit callback runs outside the lock but only ever for the serving molecule. On departure, decrement left; when it hits zero, reset it to 3, increment serving, and wake everyone.
import threading
from collections import deque
class WaterCoordinator:
def __init__(self):
self.cv = threading.Condition()
self.waitH, self.waitO = deque(), deque()
self.nextId = 0
self.serving = 0
self.left = 3
def _arrive(self, pool):
ticket = [None]
with self.cv:
pool.append(ticket)
if len(self.waitH) >= 2 and len(self.waitO) >= 1:
mid = self.nextId
self.nextId += 1
for t in (self.waitH.popleft(), self.waitH.popleft(),
self.waitO.popleft()):
t[0] = mid
self.cv.notify_all()
while ticket[0] is None or ticket[0] != self.serving:
self.cv.wait()
def _depart(self):
with self.cv:
self.left -= 1
if self.left == 0:
self.left = 3
self.serving += 1
self.cv.notify_all()
def hydrogen(self, releaseH):
self._arrive(self.waitH)
releaseH()
self._depart()
def oxygen(self, releaseO):
self._arrive(self.waitO)
releaseO()
self._depart()
Correctness sketch.
- Composition: ids are assigned only under the lock, each to exactly two popped H tickets and one popped O ticket, and only ticketed threads leave the wait loop — so no unbonded atom ever emits.
- Non-interleaving: a thread emits only when its id equals
serving, andservingadvances only when all three members have finished emitting. - Progress: bonding is re-checked on every arrival, so the arrival that completes (2 H, 1 O) triggers it; the serving molecule always has its members either emitting or cleared to emit, so
servingkeeps rising. - No lost wakeups: state changes call
notify_allunder the lock, and every waiter re-checks its predicate in awhileloop, which also absorbs spurious wakeups. - Fairness: the deques are FIFO, so no atom is bonded later than a later-arriving atom of the same type; molecules are served in id order.
Costs and scale
Bonding is O(1) per atom, and memory is O(number of blocked threads) — the stream length never enters. The one scaling wart is the notify_all thundering herd: every event wakes all W waiters, so wakeup cost is O(W). A production version would hand each ticket its own condition variable (or use fair, per-waiter semaphores) so an event wakes only the affected atoms, dropping that to O(1). Under an imbalanced H:O ratio, the surplus side parks — that's inherent — and a fair design guarantees the minority atoms are served in arrival order rather than being starved by churn.
Pitfalls to name explicitly
- Returning a permit before emitting → interleaving between consecutive molecules.
- Using a non-FIFO semaphore and claiming starvation-freedom — the two are not the same thing.
- Checking
notify/waitpredicates only once (ifinstead ofwhile), which breaks under spurious wakeups and lost signals. - Spinning on a shared counter instead of blocking, which burns CPU and violates the contract.
- Letting a coordinator thread print on behalf of atoms, which breaks the stated interface.