Gerard-Meier

Semaphore class

May 15th, 2012
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #ifndef SEMPHORE_H
  2. #define SEMPHORE_H
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <pthread.h>
  7.  
  8. using namespace std;
  9.  
  10. class Semaphore {
  11.     public:
  12.         Semaphore(int value) {
  13.             _value  = value;
  14.             pthread_mutex_init(&_mutex, NULL);
  15.             pthread_cond_init(&_cond, NULL);
  16.         }
  17.  
  18.         void wait() {
  19.             pthread_mutex_lock(&_mutex);
  20.  
  21.             --_value;
  22.  
  23.             if(_value < 0) {
  24.  
  25.                 // Rather than release all threads, it keeps blocking
  26.                 // all but one thread, hence the do... while.
  27.                 do {
  28.                     pthread_cond_wait (&_cond, &_mutex);
  29.                 } while(_wakeups < 1);
  30.  
  31.                 --_wakeups;
  32.             }
  33.  
  34.             pthread_mutex_unlock(&_mutex);
  35.         }
  36.  
  37.         void signal() {
  38.             pthread_mutex_lock(&_mutex);
  39.  
  40.             ++_value;
  41.  
  42.             if(_value <= 0) {
  43.                 ++_wakeups;
  44.                 pthread_cond_signal(&_cond);
  45.             }
  46.  
  47.             pthread_mutex_unlock(&_mutex);
  48.         }
  49.     private:
  50.         int _value;
  51.         int _wakeups;
  52.         pthread_mutex_t _mutex;
  53.         pthread_cond_t _cond;
  54. };
  55.  
  56.  
  57. #endif  /* SEMPHORE_H */
Advertisement
Add Comment
Please, Sign In to add comment