Using conditional variables in Linux to implement the semaphore mechanism

Source: Internet
Author: User

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 );

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.