[cs33211] CS33211 Locks vs. semaphores vs. condition variables

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Oct 10 23:08:39 EDT 2012


> Hi Dr. Nesterenko,
> 
> Similar operations can be performed on locks and semaphores:
> 
> lock objects -> lock/unlock
> semaphore objects -> wait/signal
> 
> What is the difference between these pairs of operations and how are locks
> and semaphores different in general? The only difference I understand is
> that locks strictly allow one thread into the CS while while counting
> semaphores may allow more than 1.


Locks (also called mutexes) are a lot simpler. They can be either
locked or unlocked. Semaphores are more sophisticated. Semaphores have
an internal state variable and can be used for such tasks as
producer/consumer, barrier synchronization, etc.


> 
> Now onto condition variables...
> 
> the semaphore.h file on the website uses condition variables as part of the
> implementation. The 2 operations used on the condition variable "cv" are
> wait() and notify_one(). This pair of operations wait/notify_one() seem
> very similar to the operations used in semaphores and locks.

A condition variable is used to atomically block (suspend) the thread an give
up its lock (mutex) - that's the operation wait().

The blocked thread can unblocked (notified). Once unblocked, it waits
to get the lock back. 

   notify_one - unblocks one thread
   notify_all - unblocks all threads

The idea behind locks and CVs is that they have the same functionality
as semaphores but are more specialized. For example, take a look how
the locks and CVs are being used in the solution to the
readers/writers problem I just posted.

Thanks,
-- 
Mikhail


More information about the cs33211 mailing list