Skip to main content
Back to problems
#1117
Medium Concurrency

Building h2o

Concurrency
58.4% acceptance
Jan 13, 2026
580
194
There are two kinds of threads: oxygen and hydrogen. Group these threads to form water molecules. Threads must pass the barrier in groups of three: one O and two H.

Solution

C++
Time O(1)
Space O(1)
LeetCode
solution.cpp
#include <mutex>
#include <condition_variable>
#include <functional>
using namespace std;

class H2O {
  mutex mtx;
  condition_variable cv;
  int h_count = 0;
public:
  H2O() {}

  void hydrogen(function<void()> releaseHydrogen) {
    unique_lock<mutex> lock(mtx);
    cv.wait(lock, [this]{ return h_count < 2; });
    releaseHydrogen();
    h_count++;
    cv.notify_all();
  }

  void oxygen(function<void()> releaseOxygen) {
    unique_lock<mutex> lock(mtx);
    cv.wait(lock, [this]{ return h_count == 2; });
    releaseOxygen();
    h_count = 0;
    cv.notify_all();
  }
};