Concurrency: Build H2O from concurrent H and O actions
Context
You are given two kinds of threads that repeatedly call the following functions:
-
hydrogen(releaseHydrogen)
-
oxygen(releaseOxygen)
Each function receives a callable action:
-
releaseHydrogen() emits/prints "H"
-
releaseOxygen() emits/prints "O"
Goal
Design synchronization so that the program outputs a valid sequence of water molecules. For every molecule, exactly two H actions and one O action must be released together (i.e., the three actions for a molecule proceed as a group; groups do not interleave).
Constraints
-
Do not busy-wait. Use semaphores, locks, and/or condition variables.
-
Safety: no extra atoms are emitted; every molecule releases exactly two H and one O.
-
Liveness: no starvation assuming both atom types arrive infinitely often.
-
Scalability: handle an unbounded stream of atoms without unbounded resource growth.
Deliverables
-
Pseudocode for hydrogen and oxygen functions and any supporting synchronization primitives.
-
A brief explanation of correctness (safety, liveness, scalability).