Sub topic 2
Peterson's Algorithm, Hardware Atomics, and Semaphores
This chapter assumes you know that processes share memory or pass messages, that a race condition occurs when two processes update shared data at the same time, and that a CPU can be preempted in the middle of a program. Each section builds on the previous one.
Peterson's algorithm for two processes
Peterson's algorithm is a software solution to the critical-section problem for two processes, numbered 0 and 1. It uses two shared variables: flag[i] says process i wants to enter, and turn says whose turn it is to yield.
int flag[2] = {0, 0};
int turn = 0;
void enter_region(int i) {
int j = 1 - i;
flag[i] = 1;
turn = j;
while (flag[j] && turn == j)
;
}
void leave_region(int i) {
flag[i] = 0;
}Both processes set turn to the other process. The last write wins, so one process always waits. This gives mutual exclusion and bounded waiting. On modern CPUs, memory reordering can break this code, so real systems need memory barriers.
Hardware support: test-and-set and compare-and-swap
Software alone struggles on modern hardware. The CPU provides atomic instructions that read and write a memory word in one indivisible step:
- Test-and-set sets a word to 1 and returns its old value.
- Compare-and-swap (CAS) writes a new value only if the word still holds an expected value.
Spinlocks and mutex locks
A spinlock is a lock that a thread acquires by repeatedly testing the lock word until it can set it. This code uses C11 atomics:
#include <stdatomic.h>
atomic_flag lock = ATOMIC_FLAG_INIT;
void acquire(void) {
while (atomic_flag_test_and_set(&lock))
;
}
void release(void) {
atomic_flag_clear(&lock);
}A mutex lets a waiting thread sleep instead of spinning. A spinlock wastes CPU time while it waits, so it suits short critical sections. A mutex suits longer ones.
Semaphores: wait, signal, binary and counting
A semaphore is an integer managed by the OS. wait(s) decrements it and blocks if the result would be negative. signal(s) increments it and wakes a blocked process. A binary semaphore holds 0 or 1 and acts like a lock. A counting semaphore tracks a number of available resources.
| Semaphore type | Initial value | Typical use |
|---|---|---|
| Binary | 1 | Mutual exclusion |
| Counting | N | Limit access to N resources |
Tracing semaphore programs and counting outcomes
To trace a program, track the value of each semaphore after every wait and signal. Consider this exercise.
Exercise
A semaphore s starts at 0. Process P1 runs wait(s) and then prints "A". Process P2 prints "B" and then runs signal(s). Can "A" print before "B"?
Show answer
No. P1 cannot pass wait(s) until P2 calls signal(s), and P2 calls signal(s) only after it prints "B".