Chapter 0 · Section 3 of 8 · 3 min read
The idea: steps, orders and shared data
Two words that are easy to mix up
This course uses these two words in the following way. Authors differ, so check what a book or talk means by them.
- Concurrency means several tasks are in progress at overlapping times. They may take turns on one core.
- Parallelism means several tasks are running at the same instant, on different cores.
The lost update can happen with either. Even on one core, tasks can be switched at almost any point, including between a read and the write that depends on it. Parallelism makes the overlap more likely. It does not create the problem.
An order for every run
Each goroutine is a list of steps. When two goroutines run together, the machine merges the two lists into one sequence. That merged sequence is an interleaving. Within each goroutine the steps keep their order. Between goroutines, the order is up to the scheduler and the hardware.
Take our two goroutines, each with three steps: read, add, write. I enumerated every way to merge them with a short script:
- There are 20 interleavings.
- Only 2 of them lose no update: all of A before all of B, or all of B before all of A.
- The other 18 lose one.
// Counts every way two goroutines, each doing read / add / write on one
// shared counter, can interleave, and how many of those lose an update.
//
// node interleavings.mjs
const steps = ['read', 'add', 'write'];
let total = 0;
let lose = 0;
function run(i, j, state) {
if (i === steps.length && j === steps.length) {
total++;
if (state.shared !== 2) lose++;
return;
}
if (i < steps.length) run(i + 1, j, apply(state, 'A', steps[i]));
if (j < steps.length) run(i, j + 1, apply(state, 'B', steps[j]));
}
function apply(state, who, step) {
const next = { shared: state.shared, A: { ...state.A }, B: { ...state.B } };
const g = next[who];
if (step === 'read') g.reg = next.shared;
if (step === 'add') g.reg += 1;
if (step === 'write') next.shared = g.reg;
return next;
}
run(0, 0, { shared: 0, A: { reg: 0 }, B: { reg: 0 } });
console.log(`${total} interleavings, ${lose} lose an update, ${total - lose} do not.`);Two goroutines with three steps each is about the smallest case there is. The number of interleavings grows quickly: for two goroutines with n steps each it is the number of ways to choose which n of the 2*n* positions belong to the first one. Add more goroutines or more steps and you can never try them all in a test. You need a way to reason about every interleaving at once. Locks, atomic operations and channels are the tools for that, and the rest of the course is about them.
Shared data and the data race
The Go documentation defines the problem like this:
A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write.
Source: Data Race Detector, go.dev.
Each part matters:
- Two goroutines, and the same variable. If each goroutine has its own data, there is nothing to race on.
- Concurrently. That means nothing orders the two accesses. Chapter 33 defines exactly what "ordered" means.
- At least one write. Two goroutines that only read the same value are fine.
In our counter, A and B both read and both write count, so every pair of accesses qualifies.
Why testing alone does not catch it
The result of a racy program can change from run to run. This is called being nondeterministic. The program is not random. The outcome depends on timing that you do not control: other load on the machine, the number of cores, the scheduler's mood. If the unlucky timing is rare, you can run the test a thousand times and never see it. In the simulator you saw the same thing: lowering Switching made the bug disappear from most runs without changing a line of the program.
So we use tools that do not depend on luck:
- Detectors that watch a run and report accesses that were not ordered, even when the wrong answer did not happen this time. Go's race detector is one, and you will run it in the next section.
- Design rules that make the bug impossible to write, such as not sharing data.
Three ways out
There are three basic ways to deal with shared data. This framing is the course's, not a rule from a standard.
- Do not share. Give each goroutine its own data, or pass data from one goroutine to another so only one owns it at a time. Go's channels are built for this (Part 2).
- Share, but never change. Data that nobody writes cannot race.
- Share and coordinate. Use a lock or an atomic operation so that accesses are ordered (Part 1).
Chapter 1 starts with the third way and the most common tool for it: the mutex.