1 class noncopyable 2 { 3 public: 4 noncopyable(){} 5 ~noncopyable(){} 6 private: 7 noncopyable(const noncopyable &){} 8 noncopyable &operator=(const noncopyable&){} 9 }; 10 11 class MyMutex : public noncopyable 12 { 13 public: 14 MyMutex(){pthread_mutex_init(&_mutex,NULL);} 15 ~MyMutex(){pthread_mutex_destroy(&_mutex);} 16 public: 17 void Lock(){pthread_mutex_lock(&_mutex);} 18 void Unlock(){pthread_mutex_unlock(&_mutex);} 19 inline pthread_mutex_t &get(){return _mutex;} 20 private: 21 pthread_mutex_t _mutex; 22 }; 23 24 class MyMutexGuard : public noncopyable 25 { 26 public: 27 explicit MyMutexGuard(MyMutex &mutex) : _mutex(mutex){_mutex.Lock();} 28 ~MyMutexGuard(){_mutex.Unlock();} 29 private: 30 MyMutex& _mutex; 31 }; 32 33 class MyContidition : public noncopyable 34 { 35 public: 36 explicit MyContidition(MyMutex &mutex) : _mutex(mutex.get()){ 37 pthread_cond_init(&_cond,NULL); 38 } 39 ~MyContidition(){} 40 public: 41 void notify(){pthread_cond_signal(&_cond);} 42 void notifyall(){pthread_cond_broadcast(&_cond);} 43 void wait(){pthread_cond_wait(&_cond,&_mutex);} 44 private: 45 pthread_cond_t _cond; 46 pthread_mutex_t& _mutex; 47 }; 48 49 50 class CountDownLatch : public noncopyable 51 { 52 public: 53 explicit CountDownLatch(int count) : _count(count),_cond(_mutex){} 54 ~CountDownLatch(){} 55 private: 56 int _count; 57 MyMutex _mutex; 58 MyContidition _cond; 59 public: 60 void CountDown(){ 61 MyMutexGuard __access__(_mutex); 62 --_count; 63 if(_count == 0){ 64 _cond.notifyall(); 65 } 66 } 67 68 void Wait(){ 69 MyMutexGuard __access__(_mutex); 70 if(_count > 0){ 71 _cond.wait(); 72 } 73 } 74 };