接上一篇《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);
}