There are two kinds of threads, oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.
In other words:
Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.
Example 1:
Input: "HOH"
Output: "HHO"
Explanation: "HOH" and "OHH" are also valid answers.
Example 2:
Input: "OOHHHH"
Output: "HHOHHO"
Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.
Constraints:
class H2O {
private:
std::mutex mutex_{};
std::condition_variable condition_variable_{};
int step = 0;
public:
H2O() {
}
void hydrogen(const std::function<void()>& releaseHydrogen) {
std::unique_lock unique_lock_{mutex_};
condition_variable_.wait(unique_lock_, [&](){return step <= 1;});
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
step += 1;
condition_variable_.notify_all();
}
void oxygen(const std::function<void()>& releaseOxygen) {
std::unique_lock unique_lock_{mutex_};
condition_variable_.wait(unique_lock_, [&](){return step == 2;});
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
step = 0;
condition_variable_.notify_all();
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有