转自:http://originlee.com/2015/01/21/trick-in-conditon-variable/
1 class ConditionBase 2 { 3 public: 4 ConditionBase() 5 { 6 pthread_mutex_init(&mutex_, NULL); 7 pthread_cond_init(&cond_, NULL); 8 } 9 10 ~ConditionBase() 11 { 12 pthread_mutex_destroy(&mutex_); 13 pthread_cond_destroy(&cond_); 14 } 15 16 private: 17 pthread_mutex_t mutex_; 18 pthread_cond_t cond_; 19 }; 20 class Condition4 : public ConditionBase 21 { 22 public: 23 Condition4() 24 : signal_(false) 25 { 26 } 27 28 void wait() 29 { 30 pthread_mutex_lock(&mutex_); 31 while (!signal_) 32 { 33 pthread_cond_wait(&cond_, &mutex_); 34 } 35 signal_ = false; 36 pthread_mutex_unlock(&mutex_); 37 } 38 39 void wakeup() 40 { 41 pthread_mutex_lock(&mutex_); 42 signal_ = true; 43 pthread_cond_signal(&cond_); 44 pthread_mutex_unlock(&mutex_); 45 } 46 47 private: 48 bool signal_; 49 };
附录:惊群效应
https://blog.csdn.net/lyztyycode/article/details/78648798