Mutual Exclusion with Binary Semaphores
You'll learn how to use a binary semaphore initialized to 1 to protect critical sections and guarantee that only one thread or process accesses shared resources at a time.
The Core Idea
A binary semaphore is like a single-key locker for your critical section. By initializing it to 1 (unlocked), the first thread that calls wait() successfully "takes the key," decrementing the semaphore to 0. Any other thread attempting wait() will block (wait) because the semaphore is now 0. When the first thread finishes and calls signal(), it increments the semaphore back to 1, "returning the key" and allowing one waiting thread to proceed.
How It Works
- Initialize the binary semaphore to 1 (critical section available)
- Before entering the critical section, call
wait()(also called P operation)- If semaphore = 1, decrement to 0 and enter
- If semaphore = 0, block and wait
- Execute your critical section code
- After exiting, call
signal()(also called V operation)- Increment semaphore back to 1
- Wake one waiting thread if any exist
The Locker Analogy
Think of a single bathroom with one key hanging on a hook outside. The semaphore value (1 or 0) represents whether the key is available. You take the key (wait()), use the bathroom (critical section), then return the key (signal()). If someone else tries to enter while you're inside, they see no key and must wait outside.
This pattern satisfies mutual exclusion: the binary semaphore ensures only one thread holds the "key" at any moment, preventing race conditions on shared data.
Key Takeaway:
A binary semaphore initialized to 1 acts as a lock—calling wait() before and signal() after a critical section guarantees mutual exclusion by allowing only one thread access at a time.