Multiple processes/threads access shared resources concurrently, leading to race conditions (incorrect results when operations interleave). We need a synchronization mechanism to coordinate access.
A semaphore is an integer variable with two atomic operations (wait/signal) used to control access to shared resources and prevent race conditions.
- Semaphore has integer value (initialized to N = number of available resources)
- wait() (P operation): Decrement semaphore; if negative, block the process
- signal() (V operation): Increment semaphore; if was negative, wake up a blocked process
- Operations are atomic (cannot be interrupted mid-execution)
- Atomic operations (wait/signal) prevent race conditions
- Can be binary (0/1) for mutual exclusion
- Can be counting (0..N) for resource pools
- Used to solve producer-consumer, reader-writer problems
- Built from: Race Condition, Critical Section
- Builds into: Binary Semaphore, Counting Semaphore
- Related: Producer-Consumer Problem, Reader-Writer Problem
- Contrasts with: Mutex (binary semaphore = mutex, but semaphore can be >1)
- Busy waiting in some implementations wastes CPU
- Deadlock if processes wait for each other circularly
- Priority inversion: high-priority process blocked by lower-priority holder