Skip to content

Shared memory

Two threads, one counter

The smallest possible race, the lock that fixes it, and what the lock actually costs.

12 minutes · critical section · mutual exclusion · mutex

One line, three operations

`n = n + 1` is a read, an add and a write. Between the read and the write another thread can do the whole thing, and its result is then overwritten by yours. Two increments, one net change.

In the async track this took two network round trips to go wrong. Here it takes one preemption, which is why the shared-memory version is the honest picture of what was happening all along.

Everything you do here stays in this browser.