Semaphores for Mutual Exclusion
The Mutual Exclusion Problem
Multiple threads want to access a shared resource, but only one should access it at a time. This is the critical section problem.
How It Works
The semaphore starts at 1. First thread calls wait(), decrements to 0, enters critical section. Second thread calls wait(), tries to decrement but would go negative, so it blocks. When first thread calls signal(), semaphore goes back to 1, and second thread wakes up.
Think Of It Like A Bathroom Key
A coffee shop has one bathroom key. Take the key (wait) to enter. Return the key (signal) when done. If someone has the key, you wait in line. The semaphore count is 1 if key is available, 0 if taken.
Symmetric Property
Any thread can enter. The first one to call wait() wins. There is no "owner" of a semaphore. This is both a feature and a danger.