previous | start | next

Synchoronization using Semaphores

Suppose thread 1 must wait at position A in its code until thread 2 has arrived at position B in its code:

  thread 1             thread 2
  .                    .
  .                    .
  .                    .
  .                    .
A:                     .
  .                    .
  .                    .
  .                  B:

This isn't a mutual exclusion problem.

Use a semaphore s with initial value 0!

// shared
sem_t s;

sem_init(&s, 0, 0);

Then insert semaphore calls in the code of the two threads:

  thread 1                      thread 2                  
  .                             .                 
  .                             .                 
  .                             .                 
  .                             .                 
A: sem_wait(&s)             .
  .                             .                 
  .                             .                 
  .                           B: sem_post(&s);

What if thread 2 gets to B before thread 1 reaches A?

What if thread 1 gets to A before thread B reaches B?



previous | start | next