KatInterview

Coordinating Hydrogen and Oxygen Threads into Complete Water Molecules

System DesignModel answer
MediumModel answerSystem Designconcurrencysynchronizationsemaphores

Last 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/emits H and must be executed by that same calling thread.
  • oxygen(releaseOxygen) — invoked by an oxygen-producing thread; the callback prints/emits O on 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:

  1. Valid grouping: if you cut the entire output stream into consecutive chunks of three characters, every chunk contains exactly two H and one O (the order inside a chunk is free).
  2. 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.
  3. 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).
  4. No busy-waiting: waiting must block, using semaphores, mutexes, or condition variables — never spin loops.
  5. 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.