Skip to content
BIASED

Synchronization

Block 1 of 4~2 min

The lost update

Two threads each run counter++ a million times — expect 2,000,000; at -O0 you get ~1e6. On RISC-V that is lw / addi / sw. Of 20 interleavings 18 lose an update: both loaded the same value.

Dijkstra’s semaphore is an integer with two atomic operations (Dijkstra, 1965): P, or sem_wait, waits until the value is positive and then decrements it; V, or sem_post, increments it and wakes a waiter if there is one. A semaphore initialized to 1 is a lock: sem_wait enters, sem_post leaves. A semaphore initialized to nnn admits up to nnn threads at once, for example to limit the number of open connections. A semaphore initialized to 0 is a signal: one thread waits on it until another posts.

A critical section is a piece of code that accesses shared data and must not run in two threads at once; here, the three instructions of counter++. A solution to the critical-section problem must guarantee mutual exclusion (at most one thread inside at a time), progress (if the section is free and some threads want to enter, one of them gets in) and bounded waiting (a thread that asked to enter is not overtaken forever) (Arpaci-Dusseau, 2018, chapter 28).

Answers are saved on the server and tied to this browser until you sign in.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Lost update and a critical sectionoptional

    Two threads +=1 without/with mutex: show the counter race and fix it with a critical section.

    ~20 min · easier on a computer · The matching course topic has been read.

    Self-check in the notebook — not part of mastery or the certificate.