← Questions

Building H2O: synchronize hydrogen and oxygen threads

0
TeslaCodingLast asked Aug 2025

Threads keep arriving, each carrying one atom: hydrogen (H) or oxygen (O). Each thread must wait until it can be part of a water molecule, then release its atom. Make sure that atoms are released in complete molecules: for every molecule, exactly two H threads and one O thread pass together, and no thread of the next molecule passes before all three of the current one have.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class H2O with hydrogen(release_hydrogen: Callable[[], None]) -> None and oxygen(release_oxygen: Callable[[], None]) -> None. Each method is called by its own thread, blocks until its molecule is formed, then calls the release function once.

Example

input threads:  "OOHHHH"
valid outputs:  "HHOHHO", "HOHHHO", "OHHHOH", ...    # each group of three has two H and one O
invalid:        "HHHHOO"                            # the first three atoms are all H

Constraints

  • The number of H threads is exactly twice the number of O threads.
  • No busy-waiting: use semaphores, locks, condition variables or a barrier.
  • The stream of atoms may be unbounded.

Clarifying questions

  • Is the input always balanced (2 H per O)? What should happen to leftover atoms if not?
  • Must the order inside one molecule be fixed (for example H, H, O)?
  • Does fairness matter: must waiting threads be served in arrival order?

What a strong answer covers

  • Safety: never more than two H or one O inside the current molecule. A common design: a semaphore with 2 permits for H, one with 1 permit for O, and a barrier of 3 that releases the group and then resets the permits.
  • Liveness: no deadlock and no starvation under an unbounded stream; why the barrier must be reusable.
  • An alternative with one lock and a condition variable that counts waiting H and O threads.
  • Pseudocode or real code, plus an argument for why molecules cannot interleave.
  • How you would test it: many threads, random arrival order, check every group of three in the output.

Follow-ups

  • Generalize to any molecule, such as C2H6, given as a count per atom.
  • Leftover atoms at shutdown must be released or cancelled cleanly.
  • Measure throughput with thousands of threads. Where is the contention?
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding