Back when I taught C programming labs, a student asked what was the difference between a Mutex and a Semaphore. My simple explination is below. Little did I know, Niclas Winquist came up with the same explanation in 2005. To me, this really is the best explanation for a non-technical audience.
Mutex is also called “Mutual Exclusion”. The explanation is in the name, really. A Mutex is a bit like a bathroom on an airplane; cramped and piss on the floor.
- You enter the bathroom
- You lock the door
- You do your business
- You unlock the door
- You leave the bathroom
Unless you are incredibly lucky or incredibly stupid, two people CANNOT be in the bathroom at the same time.
A Semaphore (flag) is a lot like bathrooms in a fancy hotel; nice heated seats and proper toilet paper. Let’s assume that there are 4 cubicles.
- Andrew enters and locks his cubicle door
- 3 Cubicle’s are free
- Bob enters and locks his cubicle door
- 2 Cubicle’s are free
- Chris enters and locks his door
- 1 Cubicle is free
- David enters cubicle and locks his door
- No Cubicles are free
- Edward waits
- Bob is finished and leaves the cubicle – unlocking it
- Edward enters and locks his door
What this means is, if there are N toilets and M people where M > N, someone will have to wait until there is a free toilet before they can proceed.