27 Jul 2023PythonMedium

Building H2O

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

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.

Solution files

PythonPython/building-h2o/solution.py

Solution file content could not be loaded.