Imagine a molecular assembly line where oxygen and hydrogen threads arrive randomly, but they must form water molecules (HโO) in perfect groups of three: exactly 2 hydrogen + 1 oxygen.
Your challenge is to implement a synchronization barrier that ensures threads pass through in complete molecular sets. No thread can proceed alone - they must wait for their molecular partners!
The Rules:
- ๐งช Perfect Molecules: Every group of 3 threads must contain exactly 2 hydrogen and 1 oxygen
- โณ Patient Waiting: If an oxygen thread arrives but there aren't 2 hydrogen threads ready, it must wait
- ๐ Complete Bonding: All 3 threads from one molecule must bond completely before any threads from the next molecule start
- ๐ฏ Atomic Groups: Threads pass the barrier in indivisible groups of three
You'll implement two methods: hydrogen() and oxygen() that handle the synchronization logic. Each method calls releaseHydrogen() or releaseOxygen() respectively when it's safe to proceed.
Input & Output
Visualization
Time & Space Complexity
Each thread operation is constant time with proper synchronization
Fixed number of semaphores regardless of thread count
Constraints
- 1 โค total threads โค 1000
- Each thread is either hydrogen ('H') or oxygen ('O')
- Threads may arrive in any order
- Must guarantee atomic molecule formation
- Solution must be thread-safe and deadlock-free