Section 9.1

Concurrency versus parallelism

Definition

Concurrency means that two or more activities are in progress during overlapping periods, so that steps of one can run between steps of another. The activities can be threads (sequences of instructions that a scheduler starts and pauses) or an interrupt handler §6.12, a routine that a device signal starts, and the code it suspends. Parallelism means that steps of different activities run at the same instant on separate hardware, such as two processor cores. Concurrency concerns possible orders of steps; parallelism concerns simultaneous execution. One core gives concurrency without parallelism.

The idea

A common line of reasoning goes: a processor with one core does one thing at a time, so data shared inside the program needs no protection. The premise is true and the conclusion is false. Take a small device whose main loop counts received packets in a variable count, while an interrupt handler, the routine the processor runs when a timer or another device signals an event, also adds to count. The two never execute at the same instant, because there is only one core. But the handler can run between any two instructions of the main loop, and the single statement count++ is three instructions. If the handler runs in the middle of them, one increment is lost.

The useful question is therefore not how many cores there are, but which activities can run between which steps. Rob Pike put the distinction this way in a 2012 talk [291]: concurrency is about dealing with lots of things at once, parallelism is about doing lots of things at once. One cook who keeps three pans going by switching between them works concurrently. Two cooks stirring two pans at the same moment work in parallel. The picture stops being accurate at one point. The cook chooses when to switch, at a convenient moment. An interrupt §6.11 switches the processor between almost any two instructions, without the agreement of the code it suspends.

How it works

Two mechanisms make activities concurrent on a single core.

Parallelism needs separate pieces of hardware that work at the same time.

Parallel activities are always concurrent as well, because their periods of activity overlap. Concurrency does not need parallelism.

To reason about a concurrent program, break each activity into its indivisible steps, the steps that nothing can split. On one core, interrupts are taken between machine instructions, so an indivisible step is normally one instruction, and a single statement of a C program can be several instructions. On a 32-bit Arm Cortex-M processor, a compiler typically turns count++ on a variable in memory into three instructions:

LDR r1, [r0] load count from memory into register r1
ADDS r1, r1, #1 add 1 to the register
STR r1, [r0] store the register back into count

A register is a small storage cell inside the processor. Between the load and the store, the new value exists only in r1, where no other activity can see it. Any change that another activity makes to count in that gap is overwritten by the store.

Synchronization must keep out every activity that could enter the gap, whichever way it gets in. On one core, masking interrupts around the three instructions, which tells the processor to hold back interrupts until they are unmasked, keeps the handler out of the gap. With two cores, masking interrupts on one core does not stop the other core. The update then needs an atomic operation §9.8, which reads, modifies and writes the memory as one indivisible step for every core, or a lock that both cores use.

Worked example

Let count start at 3. The main loop executes count++ once and the interrupt handler executes count++ once, so the correct result is 3+1+1=53 + 1 + 1 = 5. The processor saves the main loop’s registers when the interrupt starts and restores them when the handler returns, so r1 keeps its value across the handler. The handler runs as one block between two instructions of the main loop, so it can run at one of four points:

  1. Before the load. The handler changes 3 to 4. The main loop then loads 4 and stores 5. Result 5, correct.

  2. After the load. The main loop holds 3 in r1. The handler loads 3 and stores 4. The main loop adds 1 to its 3 and stores 4. Result 4: the handler’s increment is lost.

  3. After the add. The main loop holds 4 in r1. The handler loads 3 and stores 4. The main loop stores its own 4. Result 4, again wrong.

  4. After the store. The main loop has stored 4. The handler loads 4 and stores 5. Result 5, correct.

Two of the four orders lose an update, and at no moment did two instructions run at the same instant.

Rare is not the same as safe. For an estimate, assume a clock of 64 million cycles per second, so one cycle lasts 1/(64×106)1 / (64 \times 10^{6}) s, which is 15.625 ns (nanoseconds), and assume that an interrupt lands in the gap when it arrives during a window of 2 cycles, 2×15.625=31.252 \times 15.625 = 31.25 ns. With 1,000 increments per second, the main loop spends 1000×31.25=31,2501000 \times 31.25 = 31{,}250 ns, a fraction 3.125×10−53.125 \times 10^{-5} of every second, inside the window. With 10,000 interrupts per second at random moments, 10,000×3.125×10−5=0.312510{,}000 \times 3.125 \times 10^{-5} = 0.3125 of them per second land in the window: one lost update every 1/0.3125=3.21 / 0.3125 = 3.2 seconds on average, 0.3125×86,400=27,0000.3125 \times 86{,}400 = 27{,}000 per day. A one-second test often sees none.

The repair on one core: mask interrupts from before the load to after the store. An interrupt that arrives in the gap then stays pending, and its handler runs after the store, which is case 4. The result is always 5.

Stated precisely

Treat each activity as a sequence of indivisible steps, and an execution as the order in which all the steps of all the activities happen. Activity AA is active from the instant sAs_A at which its first step starts to the instant eAe_A at which its last step ends; sBs_B and eBe_B are the same instants for activity BB. AA and BB are concurrent in an execution when these periods overlap, that is, when sA<eBs_A < e_B and sB<eAs_B < e_A. They are parallel when, at some instant, a step of AA and a step of BB are both in progress. Every parallel pair is concurrent. When all the activities run on one core, no pair is parallel. A program is concurrent when its executions can contain concurrent activities.

On one core, every execution is an interleaving: one sequence that contains every step of every activity and keeps each activity’s own steps in program order. Two threads of mm and nn steps, which the scheduler may switch after any step, have (m+n)!/(m!n!)(m+n)! / (m!\, n!) interleavings, where k!k! is the product 1×2×…×k1 \times 2 \times \dots \times k; this counts the ways to choose which mm of the m+nm+n positions belong to the first thread. For m=n=3m = n = 3, that is 720/(6×6)=20720 / (6 \times 6) = 20. An interrupt handler that runs to its end is inserted as one block, so it has only m+1m + 1 possible places among mm steps: for the three instructions of count++, the four cases of the worked example.

The interleaving model is exact for one core. With several cores, it holds only for programs whose shared accesses are all synchronized, because compilers and processors may reorder unsynchronized memory accesses. The data race §9.3 and sequential consistency §9.12 entries state the conditions.

Limits and common mistakes

Masking interrupts is a single-core tool. It does not stop another core, a DMA engine, or an interrupt that the mask leaves enabled, and every masked interrupt waits until the mask is lifted.

Concurrency causes failures only through shared state that one activity changes while another uses it: a variable, a buffer, a device register or a file. Activities that share nothing, or share only data that never changes, can interleave freely.

The words differ from everyday speech, where concurrent means simultaneous. In computing, concurrent means overlapping in time, which includes taking turns on one core.

Parallelism also exists inside one instruction stream. A processor pipeline works on several instructions at once, and a vector instruction adds several pairs of numbers at once, yet the program has one sequence of steps and nothing to interleave. Such parallelism is not concurrency of the program.

The worked example describes machine instructions. A C program in which two threads access a plain shared variable without synchronization contains a data race, which the C standard leaves undefined. The C program must use atomic operations or locks; it cannot rely on the instruction-level picture.

Questions answered

How can an interrupt create a race without two CPU cores?

An interrupt creates a race on a single core by running its handler between two instructions of an operation that the interrupted code needs to be indivisible. A race here means that the result depends on when the interrupt arrives. Take count++, which the processor executes as three instructions: load count into a register, add 1, store the register back. If the interrupt handler, which also increments count, runs after the load and before the store, the interrupted code then stores a value computed from the old count, and the handler’s increment is lost. Starting from 3, the result is 4 instead of 5. Nothing ran simultaneously. The race needs only concurrency, meaning that the handler can run between two steps of the other code. It does not need parallelism, meaning two cores executing at the same instant.

The repair makes the load, the addition and the store indivisible with respect to the handler. On a single-core processor, mask interrupts around the three instructions. Alternatively, use an atomic read-modify-write operation, which also works when there are several cores.

Related entries: Race condition (§9.2), Atomic operation (§9.8), Direct memory access (DMA) (§4.36), Interrupt (§6.11), Interrupt service routine (ISR) (§6.12), Cooperative and preemptive scheduling (§6.37). Further reading: [291].