Mutex & Semaphore’s

19 01 2009

The difference between a mutex and a semaphore is something I often forget. So while this is fresh in my mind…

Mutex: Locks a critcal section of code when in use by a thread, and unlocks it only when that thread is complete. It works on a one out, one in system but only ever allows one thread at any time. If a thread tries to access the mutex when it is locked, it is forced to wait in a queue until it is unlocked.

Semaphore: A semaphore is an extension of a mutex and also locks a critical section of code when in use by a thread. However with a semaphore you can specify how many threads are allowed simultaneous access. For example, your semaphore allows 4 simultaneous threads. Each time a thread uses the semaphore, the semaphore decreases its counter by 1 until it is zero, at which point no more threads are allowed access and are forced to queue. When a thread finishes using the semaphore, the semaphore increaes it’s counter by one to allow the next thread in the queue access.

This site provided me with the best explanation: http://geekswithblogs.net/shahed/archive/2006/06/09/81268.aspx

Also, put even simpler by this site http://www.cs.tau.ac.il/~hayim/courses/os/lecture_notes/lecture5/lecture.html :

“A mutex allows one thread inside the critical section, a semaphore allows n threads in a critical section (when the number n is given as a parameter on the initialization).”