Chapter 6: Synchronization
Output Question · Introduction
Question 1: Lost Update
Shared counter = 5. T1 executes counter = counter + 1, T2 executes counter = counter + 2; each compiles to three machine instructions. The order is: T1 LOAD, T2 LOAD, T2 ADD, T2 STORE, T1 ADD, T1 STORE. What is the final value? What are all the possible final values?
/* T1 */ /* T2 */ LOAD R1, counter LOAD R2, counter ADD R1, 1 ADD R2, 2 STORE counter, R1 STORE counter, R2
Show answer
The final value is 6: T1 read the old value (5) into its register, so it writes 6 over the 7 that T2 wrote; T2's +2 is lost.
Across the 20 possible interleavings the results are only 6, 7 and 8: 8 if they run one after the other, 7 if T1's update is lost, 6 if T2's is lost. A result that depends on the execution order is a race condition; the fix is to make the read–increment–write triple a critical section or to use an atomic increment.
Multiple Choice · Critical Section
Question 2: Strict Alternation
Two processes wait at entry with while (turn != i) ; and set turn = j on exit. While P1 is absorbed in a long noncritical task, P0 cannot enter a second time even though the critical section is empty. Which condition is violated?
B: P1, outside its critical section, blocks P0's entry; the decision to enter is postponed until P1 comes around again. Mutual exclusion holds (turn cannot have two values at once) and waiting is bounded, but the processes are forced to alternate.
Step-by-Step Trace · Software Approaches
Question 3: Peterson Trace
P0 and P1 (i is the process's own number, j = 1 − i) want to enter at the same time. The order is: P0 line 1, P1 line 1, P1 line 2, P0 line 2; then both test the condition. Which one enters the critical section?
Start: both flags are 0, nobody wants to enter. The order is traced assuming sequentially consistent memory.
P0 declares its intent: flag[0] = 1.
P1 declares its intent too: flag[1] = 1.
P1 gives the turn to P0: turn = 0.
P0 gives the turn to P1: turn = 1. P0 wrote turn last; the value 0 is overwritten.
P0: flag[1] = 1 and turn == 1 → the condition is true, P0 busy-waits.
P1: turn == 0 is false → it leaves the loop, and P1 enters the critical section.
On leaving, P1 sets flag[1] = 0; P0's condition becomes false and P0 enters. The one who gives the turn away last is the one who waits.
flag[i] = true; /* I want to enter */ turn = j; /* after you */ while (flag[j] && turn == j) ; /* busy wait */ /* critical section */ flag[i] = false;
Output Question · Memory Model
Question 4: Write-Buffer Test
Initially x = y = 0. Which (r1, r2) results are possible under sequential consistency (SC)? Which result can additionally be observed on x86 (TSO), and why?
/* T1 */ /* T2 */ x = 1; y = 1; r1 = y; r2 = x;
Show answer
SC: (0, 1), (1, 0) and (1, 1). None of the six interleavings gives (0, 0): in each thread the write comes before the read, so by the time the first read happens at least one write has completed.
TSO: (0, 0) can be observed too. Each core's write first goes into its own write buffer; the following read takes the old value from memory. x86 allows only the "write → later read" reordering; ARM and RISC-V allow more.
Remedy: a full memory barrier between the write and the read (x86 mfence, C11 atomic_thread_fence) or sequentially consistent atomics. The same reordering is what breaks Peterson's algorithm.
Multiple Choice · Memory Model
Question 5: Fixing Peterson's Algorithm
Peterson's algorithm written in C occasionally lets two threads into the critical section together on x86. Which change fixes this?
D: While the write waits in the buffer, the following read takes the old value from memory; a full barrier (or seq_cst atomics) forbids this reordering. volatile in C gives neither atomicity nor ordering; a sleep only changes timing. C breaks the algorithm itself: if turn is written first, both processes can enter.
Step-by-Step Trace · Hardware Support
Question 6: Increment with CAS
With v = 10, T1 and T2 call increment(&v). The order is: T1 reads, T2 reads, T1 CAS, T2 CAS, then T2 retries. What is the final value and how many CAS calls are made in total?
compare_and_swap(v, expected, new) is a single atomic instruction: if *v == expected it writes the new value, and in every case it returns the old value.
T1 reads the value: temp = 10. With no lock, it can be interrupted here.
T2 also reads 10. With a plain v++ an increment would be lost here.
T1's CAS finds v still 10, writes 11 and returns 10: equal to temp → it leaves the loop.
T2's CAS finds v = 11: not the expected 10, so it writes nothing and returns 11 → the loop repeats.
T2 reads the current value: temp = 11.
The final value is 12 with 3 CAS calls in total. No increment was lost and nobody held a lock (a lock-free update).
void increment(int *v) { int temp; do { temp = *v; } while (compare_and_swap(v, temp, temp + 1) != temp); }
Multiple Choice · Hardware Support
Question 7: What the TSL Spinlock Lacks
Which condition of the critical-section solution does a simple spinlock, entered with while (test_and_set(&lock)) ; and left with lock = false;, not guarantee?
A: When the lock is released, it is undefined which thread's test_and_set runs first; an unlucky thread can lose every time (starvation). The atomic instruction gives exclusion, and the ability to take a free lock at once gives progress. Bounded waiting needs a version that hands the turn over on exit using a waiting[] array.
Output Question · Locks
Question 8: Approximate Counter
On a four-core machine a per-core counter with threshold S = 4 is used. In turn, core 0 calls add() six times, core 1 three times, core 2 nine times and core 3 twice. What does get() (which returns only G) return at the end? What is the true value? In the worst case, what is the largest possible difference?
void add(int c) { lock(&local_lock[c]); local[c]++; if (local[c] >= S) { lock(&global_lock); G += local[c]; unlock(&global_lock); local[c] = 0; } unlock(&local_lock[c]); }
Show answer
| Core | Increments | Moved to G | Local remainder |
|---|---|---|---|
| 0 | 6 | 4 | 2 |
| 1 | 3 | 0 | 3 |
| 2 | 9 | 4 + 4 | 1 |
| 3 | 2 | 0 | 2 |
get() = G = 12; the true value is 20 (the difference of 8 is waiting in the local counters).
In the worst case every local counter stops at S − 1: 4 × 3 = 12. A large S goes to the global lock rarely and scales well, but the value read lags further behind.
Multiple Choice · Semaphores
Question 9: Connection Pool
At most 5 connections to a database may be open at the same time. Each thread calls wait(S) before connecting and signal(S) when it closes the connection. What should the initial value of S be?
D: The initial value of a counting semaphore is the number of resources that can be used at once: 5 threads pass and the sixth blocks. An initial 1 is the mutual-exclusion pattern (one connection only); 0 is the ordering pattern, where nobody passes until the first signal arrives.
Step-by-Step Trace · Semaphores
Question 10: Semaphore Queue Trace
On a counting semaphore starting at S = 2 (Silberschatz implementation, FIFO queue), in order: P1 wait, P2 wait, P3 wait, P1 signal, P4 wait, P5 wait, P2 signal, P3 signal. What is S at the end, who holds a resource and who is waiting?
A counting semaphore starts at 2: two identical resources are free. If the value is negative, its absolute value is the number of waiters.
P1 wait: 2 → 1, not negative → P1 takes a resource.
P2 wait: 1 → 0 → P2 passes too. Both resources are in use.
P3 wait: 0 → −1 < 0 → P3 joins the queue and sleeps.
P1 signal: −1 → 0, still ≤ 0 → P3 at the head of the queue is woken and takes the resource.
P4 wait: 0 → −1 → P4 joins the queue.
P5 wait: −1 → −2 → P5 joins the queue too. |−2| = 2 processes are waiting.
P2 signal: −2 → −1 ≤ 0 → P4 wakes.
P3 signal: −1 → 0 ≤ 0 → P5 wakes. Final state: S = 0, P4 and P5 hold the resources, the queue is empty.
wait(S) {
S->value--;
if (S->value < 0) {
add to queue; block(); }
}
signal(S) {
S->value++;
if (S->value <= 0) {
P = remove from queue; wakeup(P); }
}Output Question · Semaphores
Question 11: Possible Outputs
The semaphores x and y start at 0; two threads are started at the same time. What are all the outputs that can appear on the screen?
/* T1 */ printf("A"); signal(&x); printf("B"); wait(&y); printf("C"); /* T2 */ wait(&x); printf("D"); signal(&y); printf("E");
Show answer
The orders the semaphores force: A → D (D waits for the signal(x) that follows A), D → C (C waits for the signal(y) that follows D); in addition each thread's own order: A → B → C and D → E.
There are 5 outputs that obey these rules: ABDCE, ABDEC, ADBCE, ADBEC, ADEBC. A is always first and C always comes after D; the order of B with D, B with E and C with E is left to the scheduler.
A semaphore starting at 0 is a signal that "the event happened": if signal comes first the value becomes 1, and the following wait passes without waiting.
Step-by-Step Trace · Classic Problems
Question 12: Producer–Consumer with Semaphores
N = 2, the buffer is empty. The order is: Cons tries to take an item; Prod puts in A and B; Prod tries for C; Cons takes an item; Prod puts in C; Cons takes one more item. At each step, what are the semaphores, the buffer and the sleepers? (up wakes a sleeper if there is one, and the value stays 0.)
Buffer empty: empty = 2 free slots, full = 0 filled slots.
Cons: down(&full), full = 0 → Cons sleeps. No busy waiting.
Prod puts in A: empty 2 → 1. up(&full) wakes the sleeping Cons; Cons's down completes, and full stays 0.
Cons has not run yet; Prod puts in B too: empty 0, full 1.
Prod does down(&empty) for C: the buffer is full → Prod sleeps.
Cons runs and takes A. up(&empty) wakes the sleeping Prod; empty stays 0.
Prod puts in C: full 2.
Cons: full 2 → 1, takes B, empty 0 → 1. At the end the buffer holds C; mutex = 1, empty = 1, full = 1. When no operation is in progress, empty + full = N always.
semaphore mutex = 1, empty = 2, full = 0; void producer(void) { while (TRUE) { item = produce_item(); down(&empty); down(&mutex); insert_item(item); up(&mutex); up(&full); } } void consumer(void) { while (TRUE) { down(&full); down(&mutex); item = remove_item(); up(&mutex); up(&empty); consume_item(item); } }
Multiple Choice · Classic Problems
Question 13: Reversed down
In the bounded-buffer producer–consumer solution the producer mistakenly does down(&mutex) first and then down(&empty); the consumer has the correct order. What happens if the producer runs when the buffer is completely full?
C: The producer takes the mutex, and because empty = 0 it sleeps in down(&empty) while holding the mutex. The consumer passes down(&full) but sleeps in down(&mutex); it was the one who would have done up(&empty). Rule: wait on the counting semaphore first, then on the mutex; never sleep while holding the mutex.
Multiple Choice · Classic Problems
Question 14: A Weakness of the Readers–Writers Solution
In the readers–writers solution the first reader locks db and the last reader releases it. What happens if readers arrive continuously, overlapping one another?
D: rc never drops to 0, so up(&db) is never called; the writer starves in down(&db). Readers can read together (A is wrong) and the writer is always alone (B is wrong). Fix: while a writer waits, queue new readers behind it.
Multiple Choice · Classic Problems
Question 15: Seven Philosophers
Seven philosophers sit at a round table with 7 forks between them; each philosopher needs the two forks on the right and left to eat. At most how many philosophers can eat at the same time?
B: Each eating philosopher holds 2 forks, and two neighbors cannot eat at the same time: ⌊7 / 2⌋ = 3 (6 of the 7 forks are in use). C rounds 7 / 2 up; one of the fourth philosopher's two neighbors is always eating.
Multiple Choice · Monitors
Question 16: Why while?
A consumer written with Pthreads contains the line if (count == 0) pthread_cond_wait(&c, &m);. Why is this code wrong?
A: signal is only a hint; by the time the woken thread reacquires the mutex, another consumer may have taken the item (barging). POSIX also permits spurious wakeups. B is wrong: cond_wait releases the mutex atomically and sleeps. C is wrong: a condition variable has no value, and a signal sent when nobody is waiting is lost.
Output Question · POSIX and Java
Question 17: Lock and Semaphore Counters
What is the output of the following Java program?
ReentrantLock k = new ReentrantLock(); k.lock(); k.lock(); System.out.print(k.getHoldCount() + " "); k.unlock(); System.out.println(k.isLocked()); k.unlock(); Semaphore s = new Semaphore(2); s.acquire(); s.acquire(); System.out.print(s.tryAcquire() + " "); s.release(3); System.out.println(s.availablePermits() + " " + k.isLocked());
Show answer
2 true false 3 false
ReentrantLockis reentrant: when its owner locks twice, the hold count is 2. After one unlock the count is 1 and the lock is still held:true. The second unlock releases the lock.- After two acquires on a semaphore with 2 permits, no permits remain:
tryAcquire()returnsfalsewithout waiting. release(3)raises the value by 3; a Java semaphore does not treat the initial value as an upper bound:3. The finalisLocked()isfalse.
Output Question · Liveness
Question 18: Priority Inversion Calculation
One CPU, preemptive priority (H > M > L). L takes the lock at t = 0, and its critical section lasts 4 units. H arrives at t = 1 and immediately requests the same lock; once it has the lock it runs for 2 units. M arrives at t = 2, runs for 5 units and does not use the lock. Without and with priority inheritance, how many units does H wait for the lock, and when does it finish?
Show answer
Without inheritance, M, which has nothing to do with the lock, keeps H waiting: priority inversion. The longer M runs, the longer the wait, without bound. With inheritance, L runs with H's priority from the moment H blocks; M cannot get in between, and L releases the lock at 4.
Multiple Choice · Liveness
Question 19: Polite Threads
Two threads each want two locks. A thread that cannot get the second lock with trylock releases the one it holds and retries after the same delay every time. Both keep running continuously, but neither can finish its work. What is this situation called, and what is the correct description?
C: In a livelock the processes are not blocked; they keep changing state but no progress is made. Remedy: random (exponential) backoff or lock ordering. In a deadlock the threads sleep; in starvation at least one makes progress.
Multiple Choice · Lock-Free Programming
Question 20: The ABA Problem
In a lock-free stack, T1 reads top = A and A.next = B for a pop, then is preempted. Meanwhile T2 pops A, pops B and pushes A back. T1's CAS(top, A, B) call succeeds, but the stack is corrupted. What is the problem called, and what is the remedy?
A: CAS looks only at equality of the value; it does not notice that top changed A → B → A, and it makes top point to B, which is no longer on the stack. Remedy: compare together with a version counter that grows on every change, or do not reuse a freed node without safe reclamation (hazard pointers, epochs).