The barrier puzzle
Threads represent hydrogen and oxygen atoms. To form a water molecule exactly two hydrogen and one oxygen must group together. No atom may bond until a complete set of three is ready, and surplus atoms must wait for their own molecule.
Why it is a grouping barrier
This is a barrier that fires in batches with a fixed composition. Unlike a simple barrier that waits for a count, here the count must be split by type, two of one and one of the other, before release.
A semaphore solution
Use one semaphore for hydrogen and one for oxygen, a mutex for counts, and a reusable barrier of size three:
- A hydrogen thread increments the hydrogen count. If two hydrogen and one oxygen are present it releases two hydrogen and one oxygen, otherwise it waits.
- An oxygen thread does the symmetric check.
- All three reach the barrier so the molecule forms before any thread proceeds to the next round.
The barrier ensures the three bonding atoms leave together and no atom from the next molecule sneaks in early.
Key idea
Building H2O is a typed batch barrier that releases exactly two hydrogen and one oxygen together, using counts and a size three barrier to bond each molecule cleanly.