zenCPE333 / Operating Systems
← Library

Lock Mechanisms

Compare atomic instructions, fairness, spinning and sleeping.

Take a number: ticket lock

1 of 4

Thread Ano ticket
Shared locknext 0 / turn 0
Thread Bno ticket

The next ticket and serving turn start at 0.

Race for the lock

What makes a good lock?

Evaluate correctness (mutual exclusion), fairness (including starvation), and performance under different contention and CPU conditions. Disabling interrupts is privileged and does not stop other CPUs. Separate ordinary load and store instructions cannot safely claim an unlocked flag.

Atomic hardware primitives

Test-and-set swaps in a new value and returns the old one. Compare-and-swap only changes the value if it matches the expected one. Fetch-and-add returns the old value while incrementing; a ticket lock serves tickets in order using a separate turn counter. Real implementations also require proper memory ordering.

Spin, yield or park?

Spinning repeatedly checks readiness and wastes CPU if the owner cannot run. Yield lets the scheduler try another runnable thread, but does not guarantee fairness. A guarded queue lets contenders sleep. Coordinate enqueue and sleep with wakeup (e.g. park preparation or a conditional wait) so a wake cannot disappear just before the contender parks.

Compare implementations

Mechanism What changes state Main limitation
Disable interrupts CPU defers local interrupts Privileged; does not stop other cores
Separate test and set Ordinary read then write Two callers can both observe 0 and enter
Atomic test-and-set Always writes and returns old value Correct exclusion but not FIFO
Compare-and-swap Writes only when the old value equals the expected value Spinning CAS does not ensure fairness
Fetch-and-add Increments and returns the old ticket FIFO order, but still spins
Guarded queue Enqueues and hands off to the next waiter Must coordinate sleep and wakeup

Mutual exclusion means never two owners. Progress means somebody can enter; starvation freedom means each waiter eventually enters under the scheduling assumptions. The lecture mentions Peterson’s algorithm as an example of software locking, unlike the broken naive test–set pair. With a preempted owner and N contenders, spinning can waste N−1 time slices. Yield moves a thread from running to ready, not asleep, so it can repeatedly be scheduled and yield without making progress.

sequenceDiagram
accTitle: Queued lock handoff
participant W as Waiter
participant O as Owner
W->>W: Guard, enqueue, prepare to park
W->>W: Release guard and park
O->>O: Guard and dequeue waiter
O->>W: Hand off lock and unpark

The guard protects queue and lock bookkeeping, not the user’s critical section. Solaris setpark() handles the early-wake race by making a pending park return immediately; Linux futex waiting can check that the state is still as expected before sleeping. A two-phase lock spins briefly then blocks, balancing short handoff latency against wasted CPU when the owner is delayed.

Exam focus: trace the lock flag, guard, and queue

A spinlock needs an atomic check-and-claim. A sleeping lock also needs to handle a wake that arrives before park.

Watch two threads race for one lock

Start each example with flag = 0 (free). flag = 1 means held. Read downward in time.

Separate check and write — broken (PDF pages 8–11)

Step Thread A Thread B Shared flag after step
1 Reads 0, leaves the loop, then pauses — 0
2 — Reads 0 and leaves the loop too 0
3 — Writes 1 and enters 1
4 Resumes, writes 1 and enters Still inside 1

At step 4, A does not recheck the flag. Both threads are inside. The problem is the gap between seeing a free lock and claiming it.

Atomic check and claim — one owner (PDF pages 13–18)

sequenceDiagram
accTitle: Only the first atomic claim takes the lock
participant A as Thread A
participant F as Shared flag
participant B as Thread B
Note over F: Starts free at 0
A->>F: Atomic claim
F-->>A: Old value 0, flag now 1
Note over A: Enters
B->>F: Atomic claim
F-->>B: Old value 1, flag stays 1
Note over B: Keeps spinning

Both instructions let A in and keep B waiting, but they do different things at the flag:

Operation A sees 0 B sees 1
TestAndSet(flag, 1) Writes 1, returns 0 Writes 1 again, returns 1
CAS(flag, 0, 1) Expected 0 matches: writes 1, returns 0 Expected 0 does not match: no write, returns 1

In these lecture versions, the return is the old value. A return of 0 tells a thread it claimed a free lock; a return of 1 tells it to retry. A ticket lock works differently: it hands out unique tickets and waits until the current turn matches.

Follow ownership at unlock

flowchart TB
accTitle: Queued mutex release and handoff
U[Owner takes the guard] --> Q{Any waiting threads?}
Q -->|No| F[Clear flag: lock becomes free]
Q -->|Yes| H[Remove and wake next waiter; keep flag held]
F --> G[Release guard]
H --> G

The guard protects bookkeeping, while flag protects entry into the user’s critical section. In the queued case, keep the flag held during handoff so a new caller cannot jump ahead. On PDF pages 28–30, the waiter calls setpark before releasing the guard; a wake that arrives before the actual park is then remembered.

Test yourself

1. What is wrong with a separate test and set?
2. What gives a ticket lock its ordering?
3. Why protect enqueue-to-sleep?
4. What remains a downside of a ticket spinlock?
5. A queued mutex owner hands off to a waiter. What happens to the ownership flag?