When processes/threads share data, a race condition happens if the result depends on the order they run. The code that touches shared data is the critical section.
A correct solution needs: Mutual exclusion (one at a time), Progress and Bounded waiting.
| Mutex | Semaphore |
|---|---|
| Lock with owner: only the thread that locked can unlock | Integer counter changed by wait() / signal() |
| Binary: locked / unlocked | Binary (0/1) or counting (0..n) |
| Protect one critical section | Also limits access to n identical resources |
// wait (P) and signal (V) — both are atomic
wait(S) {
while (S <= 0) ; // busy wait
S--;
}
signal(S) {
S++;
}
// usage
wait(mutex);
/* critical section */
signal(mutex);
Classic problems: Producer–Consumer (bounded buffer), Readers–Writers, Dining Philosophers.