previous | start | next

Semaphores and the Critical Section Problem

In constrast to the difficulty of solving the critical section problem using busy waiting, a simple solution can be provided using semaphores.

This use of semaphores will easily meet the mutual exclusion and the progress requirements. Depending on the implementation of the semaphores, the same code using semaphores may also meet the bounded waiting requirement.

A single semaphore with initial value of 1 is created. Each thread using the critical resource uses this semphore as below to enter and leave its critical section:

sem_t mutex; // The semaphore. Its initial value should be 1

// Thread code for entering, leaving 
// its critical section:

 sem_wait(&mutex);
 critical section
 sem_post(&mutex);

When a thread using this code is in its critical section, the value of mutex semaphore is 0. Consequently all other threads trying to execute sem_wait(&mutex) to enter their critical sections will block.

When no thread is in its critical section, the value of mutex is 1.

This works for any number of threads, not just 2.



previous | start | next