Linux下利用条件变量实现信号量机制

接上一篇《Linux下利用条件变量实现读写锁》,继续讨论如何利用pthread_cond_t来实现sem_t。目前的Linux内核都支持信号量sem_t,但也有一些老的OS,如AIX4,和早期的Solaris并不支持信号量,毕竟semaphore这个东东并没有包括在POSIX标准里。这种情况下有必要利用pthread_mutex_t + pthread_cond_t来模拟semaphore啦。(什么?pthread_mutex_t pthread_cond_t也不支持? !@#¥%!)

其实实现起来真的很简单,

class Semaphore {

protected:

 pthread_mutex_t mutex;

 pthread_cond_t cond;

 unsigned int waiters;

public:

 Semaphore();

 virtual ~Semaphore() {}

 int p();

 int v();

}

Semaphore::Semaphore() {

 mutex = PTHREAD_MUTEX_INITIALIZER;

 cond = PTHREAD_COND_INITIALIZER;

 waiters = 0;

}

int Semaphore::p() {

 pthread_mutex_lock(&mutex);

 while (waiters <= 0) {

  pthread_cond_wait(&cond, &mutex);

 }

 waiters--;

 pthread_mutex_unlock(&mutex);

}

int Semaphore::v() {

 pthread_mutex_lock(&mutex);

 waiters++;

 if (waiters > 0) {

  pthread_cond_signal(&cond);

 }

 pthread_mutex_unlock(&mutex);

}

相关推荐