Question

What is the difference between above two?

This question came to my mind because I found that

  1. Monitors and locks provide mutual exclusion

  2. Semaphores and conditional variables provide synchronization

Is this true?

Also while searching I found this article

Any clarifications please.

Was it helpful?

Solution

Mutual exclusion means that only a single thread should be able to access the shared resource at any given point of time. This avoids the race conditions between threads acquireing the resource. Monitors and Locks provide the functionality to do so.

Synchronization means that you synchronize/order the access of multiple threads to the shared resource.
Consider the example:
If you have two threads, Thread 1 & Thread 2.
Thread 1 and Thread 2 execute in parallel but before Thread 1 can execute say a statement A in its sequence it is a must that Thread 2 should execute a statement B in its sequence. What you need here is synchronization. A semaphore provides that. You put a semapohore wait before the statement A in Thread 1 and you post to the semaphore after statement B in Thread 2.
This ensures the synchronization you need.

OTHER TIPS

The best way to understand the difference is with the help of an example.Below is the program to solve the classical producer consumer problem via semaphore.To provide mutual exclusion we genrally use a binary semaphore or mutex and to provide synchronization we use counting semaphore.

BufferSize = 3;

semaphore mutex = 1;              // used for mutual exclusion
semaphore empty = BufferSize;     // used for synchronization
semaphore full = 0;               // used for synchronization

Producer()
 {
  int widget;

   while (TRUE) {                  // loop forever
     make_new(widget);             // create a new widget to put in the buffer
     down(&empty);                 // decrement the empty semaphore
     down(&mutex);                 // enter critical section
     put_item(widget);             // put widget in buffer
     up(&mutex);                   // leave critical section
     up(&full);                    // increment the full semaphore
   }
 }

Consumer()
{
  int widget;

   while (TRUE) {                  // loop forever
     down(&full);                  // decrement the full semaphore
     down(&mutex);                 // enter critical section
     remove_item(widget);          // take a widget from the buffer
     up(&mutex);                   // leave critical section
     consume_item(widget);         // consume the item
  }
}

In the above code the mutex variable provides mutual exclusion(allow only one thread to access critical section) whereas full and the empty variable are used for synchonization(to aribtrate the access of shared resource among various thread).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top