Next, we will continue to discuss how to use pthread_cond_t to implement sem_t. Currently, the Linux kernel supports sem_t, but some old OS such as aix4 and earlier Solaris do not support semaphores. After all, semaphore is not included in the POSIX standard. In this case, it is necessary to use pthread_mutex_t + pthread_cond_t to simulate semaphore. (What? Pthread_mutex_t pthread_cond_t is not supported either? ! @ # ¥ % !)
In fact, the implementation is really simple,
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 );
}