00001 00002 #ifndef __semaphore_hpp__ 00003 #define __semaphore_hpp__ 00004 00005 #include <pthread.h> 00006 00007 class Semaphore 00008 { 00009 public: 00010 Semaphore( int value = 0 ) { 00011 pthread_mutex_init( &_mutex, NULL ); 00012 pthread_cond_init( &_cond, NULL ); 00013 _count = value; 00014 } 00015 00016 ~Semaphore() { 00017 pthread_mutex_destroy( &_mutex ); 00018 pthread_cond_destroy( &_cond ); 00019 } 00020 00021 int value() { return _count; } 00022 00023 void up() { 00024 pthread_mutex_lock( &_mutex ); 00025 _count++; 00026 pthread_cond_signal( &_cond ); 00027 pthread_mutex_unlock( &_mutex ); 00028 } 00029 00030 void down() { 00031 pthread_mutex_lock( &_mutex ); 00032 if( _count == 0 ) 00033 pthread_cond_wait( &_cond, &_mutex ); 00034 _count--; 00035 pthread_mutex_unlock( &_mutex ); 00036 } 00037 private: 00038 pthread_mutex_t _mutex; 00039 pthread_cond_t _cond; 00040 int _count; 00041 }; 00042 00043 #endif // __semaphore_hpp__