Grokking Multithreading and Concurrency for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Problem 12: Building H2O
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Overview

The Building H2O problem is a classic synchronization challenge in concurrent programming. The main challenge is to ensure that two hydrogen threads and one oxygen thread are properly synchronized so that they can form a water molecule, H2O, without violating the given constraints. This scenario highlights the difficulty of coordinating multiple threads to achieve a specific sequence or grouping, making sure that they interleave in a way that leads to the correct result. It mirrors real-world situations where resources (in this case, threads) must be combined in the right proportions to achieve the desired outcome.

Pseudocode

Initialize: semaphore oxygen = 0 semaphore hydrogen = 0 mutex lock Procedure releaseOxygen(): lock.acquire() # Acquire lock to ensure atomic operations oxygen += 1 # Increment oxygen count if oxygen >= 1 and hydrogen >= 2: # Check for available threads to form a water molecule oxygen -= 1 # Decrement oxygen count hydrogen -= 2 # Decrement hydrogen count by 2 barrier.passOxygen() # Allow oxygen thread to pass the barrier barrier.passHydrogen() # Allow two hydrogen threads to pass the barrier barrier.passHydrogen() lock.release() # Release lock Procedure releaseHydrogen(): lock.acquire() # Acquire lock to ensure atomic operations hydrogen += 1 # Increment hydrogen count if oxygen >= 1 and hydrogen >= 2: # Check for available threads to form a water molecule oxygen -= 1 # Decrement oxygen count hydrogen -= 2 # Decrement hydrogen count by 2 barrier.passOxygen() # Allow oxygen thread to pass the barrier barrier.passHydrogen() # Allow two hydrogen threads to pass the barrier barrier.passHydrogen() lock.release() # Release lock

Note:

  • The pseudocode uses semaphores and a mutex to synchronize the threads.
  • The barrier.passOxygen() and barrier.passHydrogen() methods are conceptual and represent the action of the respective threads passing through the barrier and forming the water molecule.
  • The actual implementation might require more specific functions or methods depending on the programming language or environment used.

Algorithm Walkthrough

Algorithm walkthrough or dry run for the given C++ program, demonstrating the synchronization of Hydrogen and Oxygen atoms to create water molecules (H2O).

Initial Setup:

  • H2O h2o: Instantiate an H2O object.
  • hydrogenCount = 0: Initialize hydrogen atom counter.
  • Initialize mutex and condition variables.

Thread Creation:

  • t1: Hydrogen thread, calling releaseHydrogen() 10 times.
  • t2: Hydrogen thread, calling releaseHydrogen() 10 times.
  • t3: Oxygen thread, calling releaseOxygen() 10 times.

Dry Run Steps:

  1. t1 calls releaseHydrogen():

    • Locks the mutex.
    • hydrogenCount is 0, so it increments to 1.
    • Calls generateHydrogen(), printing "Hydrogen (H) generated!".
    • Unlocks the mutex.
  2. t2 calls releaseHydrogen():

    • Locks the mutex.
    • hydrogenCount is 1, so it increments to 2.
    • Calls generateHydrogen(), printing "Hydrogen (H) generated!".
    • Signals t3 because there are now 2 Hydrogen atoms.
    • Unlocks the mutex.
  3. t3 calls releaseOxygen():

    • Locks the mutex.
    • Finds 2 Hydrogen atoms available (from steps 1 and 2).
    • Resets hydrogenCount to 0.
    • Calls generateOxygen(), printing "Oxygen (O) generated!".
    • Prints "H2O is created!".
    • Broadcasts signal to Hydrogen condition variable (wakes up any waiting Hydrogen threads).
    • Unlocks the mutex.
  4. Steps 1 to 3 repeat until all threads finish their iterations.

Considerations

  • The exact order of execution can vary since thread scheduling is done by the operating system and may depend on system load, CPU availability, and other factors.
  • The above steps assume an ideal scenario where threads execute in a perfect alternating order. In a real-world scenario, you might see multiple Hydrogen atoms generated before an Oxygen atom, especially since we have two Hydrogen-generating threads and only one Oxygen-generating thread.
  • The program ensures that "H2O is created!" is printed only when there are enough atoms to form a water molecule, maintaining the chemical accuracy of the process.

By the end of the execution, you would see "Hydrogen (H) generated!", "Oxygen (O) generated!", and "H2O is created!" printed 20, 10, and 10 times, respectively, representing the formation of 10 water molecules.

Flow Chart
Flow Chart
Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible