Concurrency design problem (paper-only). Threading primitives are not available in the gitGood sandbox; the auto-grader validates a simulation of the barrier protocol. The interview-grade answer uses two semaphores plus a barrier or a monitor.
There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed (one oxygen + two hydrogens). Threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.
In other words:
- If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads.
- If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread.
For the auto-grader: given a string arrivals of 'H' and 'O' characters representing arrival order at the barrier, return the molecule release order as a string. Each molecule is encoded as the three letters that crossed the barrier together, in their barrier-release order (always two H followed by one O - "HHO"). If the input doesn't form complete molecules, only return completed ones.