# 1117.Building H2O

**1117.Building H2O**

难度:Hard

> 现在有两种线程，氢 oxygen 和氧 hydrogen，你的目标是组织这两种线程来产生水分子。

存在一个屏障（barrier）使得每个线程必须等候直到一个完整水分子能够被产生出来。

氢和氧线程会被分别给予 releaseHydrogen 和 releaseOxygen 方法来允许它们突破屏障。

这些线程应该三三成组突破屏障并能立即组合产生一个水分子。

你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。

换句话说:

如果一个氧线程到达屏障时没有氢线程到达，它必须等候直到两个氢线程到达。 如果一个氢线程到达屏障时没有其它线程到达，它必须等候直到一个氧线程和另一个氢线程到达。 书写满足这些限制条件的氢、氧线程同步代码。

```
示例 1:

输入: "HOH"
输出: "HHO"
解释: "HOH" 和 "OHH" 依然都是有效解。
示例 2:

输入: "OOHHHH"
输出: "HHOHHO"
解释: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" 和 "OHHOHH" 依然都是有效解。
 

限制条件:

输入字符串的总长将会是 3n, 1 ≤ n ≤ 50；
输入字符串中的 “H” 总数将会是 2n；
输入字符串中的 “O” 总数将会是 n。
```

输出两个H后将线程锁住输出O，然后解锁H线程。

```
class H2O {
pthread_mutex_t t1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t t2=PTHREAD_MUTEX_INITIALIZER;
int count=0;
public:
    H2O() {
        pthread_mutex_lock(&t2);
    }

    void hydrogen(function<void()> releaseHydrogen) {
        pthread_mutex_lock(&t1);
        
        // releaseHydrogen() outputs "H". Do not change or remove this line.
        releaseHydrogen();
        pthread_mutex_unlock( ++count==2 ? &t2 : &t1);

    }

    void oxygen(function<void()> releaseOxygen) {
        pthread_mutex_lock(&t2);
        count=0;
        // releaseOxygen() outputs "O". Do not change or remove this line.
        releaseOxygen();
        pthread_mutex_unlock(&t1);

    }
};
```

> 执行用时 :20 ms, 在所有 C++ 提交中击败了81.82%的用户\
> 内存消耗 :14.7 MB, 在所有 C++ 提交中击败了100.00%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/1117.building_h2o.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
