Tuesday, October 26, 2010

Semaphore implementaion using condition variables and mutex

Implementation of semaphore using condition variable and mutex

        To implement a semaphore, we need 3 important functions. A sem_post or up function, sem_wait or down function and sem_init function. At first we have to define a structure with a interger value, mutex of pthread_mutex_t type and  cond of pthread_cond_t type.
------------------------------------------------------
struct semaphore                   
{                                              
  int val;                     
         pthread_mutex_t mutex;
         pthread_cond_t cond;    
}                                            
-----------------------------------------------------

 Now we need three functions:
 --> init(semaphore *s); --contains the initial value of the semaphore.
 --> up(semaphore *s);  --increments the value of val.
 --> down(semaphore *s); -- decrements the value of val and if val is zero it waits for an up()

Code for init()
------------------------------------------------------------------------
void init(semaphore *s, int n)                                                     
{                                                                   
s->val = n;                                
}                                                                  
--------------------------------------------------------------------------
Code for up()
--------------------------------------------------------------------------
void up(semaphore *s)                                    
{                                                                      
pthread_mutex_lock(&(s->mutex));
s->val++;                                        
     pthread_cond_broadcast(&(s->cond));
pthread_mutex_lock(&(s->mutex)); 
}                                                                      
--------------------------------------------------------------------------
Code for down()
----------------------------------------------------------------------------------------
void down(semaphore *s)                                              
{                                                                                      
pthread_mutex_lock(&(s->mutex));                
while(s->val == 0)                                         
                 pthread_cond_wait(&(s->cond),&(s->mutex));
s->val--;                                                           
pthread_mutex_unlock(&(s->mutex));             
}                                                                                     
-----------------------------------------------------------------------------------------

1 comment:

  1. Why do you think a pthread_cond_broadcast is necessary (as opposed to a pthread_cond_signal call?)

    When would you need to wake up more than one consumer when a single resource was added?

    ReplyDelete