1117. H2O 生成(多线程 + 互斥量)
题目连接:
https://leetcode-cn.com/problems/building-h2o/
题目大意:
中文题目
具体思路:
首先是三个线程控制H 和 O ,通过count 来控制结果。初始化count == 2 ,当凑齐两个H 的时候,就拿出一个O 来凑对
AC代码:
1 class H2O { 2 private: 3 int countOxygen; 4 pthread_mutex_t lockHy; 5 pthread_mutex_t lockOx; 6 public: 7 H2O() { 8 pthread_mutex_init(&lockHy, NULL); 9 pthread_mutex_init(&lockOx, NULL); 10 pthread_mutex_lock(&lockOx); 11 this->countOxygen = 2; 12 } 13 void hydrogen(function<void()> releaseHydrogen) { 14 pthread_mutex_lock(&lockHy); // 获取 H 的锁 15 releaseHydrogen(); 16 this->countOxygen--; 17 if(this->countOxygen > 0){ 18 pthread_mutex_unlock(&lockHy); 19 }else{ 20 pthread_mutex_unlock(&lockOx); // 当凑齐 H 的时候,就释放 O 的锁,让 O 线程控制 O 的 获取 21 } 22 } 23 void oxygen(function<void()> releaseOxygen) { 24 pthread_mutex_lock(&lockOx); 25 releaseOxygen(); 26 this->countOxygen = 2; 27 pthread_mutex_unlock(&lockHy); // 当获取完 O 之后,就释放 H 的锁 28 } 29 };