← Questions
Building H2O: synchronize hydrogen and oxygen threads
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 H2Owithhydrogen(release_hydrogen: Callable[[], None]) -> Noneandoxygen(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
Hthreads is exactly twice the number ofOthreads. - 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
Hor oneOinside the current molecule. A common design: a semaphore with 2 permits forH, one with 1 permit forO, 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
HandOthreads. - 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?
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
