← Back to index
MediumPython4 min read

Building H2O

coordinate hydrogen and oxygen threads to form water molecules using semaphores and barrier synchronization.

concurrencythreading

Problem link

View on LeetCode

Solutions in this repo

  • Python../Python/building-h2o/solution.pyPython solution

use semaphores to limit access: hydrogen_semaphore allows 2 threads, oxygen_semaphore allows 1 thread. use barrier(3) to synchronize so all three threads (2H + 1O) wait together before releasing.

each hydrogen thread acquires hydrogen semaphore, waits at barrier, releases hydrogen, then releases semaphore. oxygen thread does same with oxygen semaphore. barrier ensures all three are ready before any proceed.

synchronization

  • hydrogen_semaphore(2): allows max 2 hydrogen threads
  • oxygen_semaphore(1): allows max 1 oxygen thread
  • barrier(3): waits for all 3 threads before proceeding
  • ensures correct H2O molecule formation

complexity

O(1) time per molecule formation. synchronization overhead depends on thread scheduling.