← Back to the chapter · Previous detail · Next detail →

Technical detail · Microcontroller Programming: Setup and GPIO

Shared state and interrupt strategies

Suppose the shared counter a starts at 10. The loop reads 10 and plans to add one. Before it writes, an interrupt reads 10, subtracts one, and writes 9. The loop then resumes with its old copy and writes 11. The handler’s update is lost. Each C statement can take several machine steps, so the two updates can interleave like this. Protect the shared update or use an appropriate atomic operation.

Latency is the time from an event to its response. Concurrency means that work in the loop and handler can make progress during the same period, even if one interrupts the other. For the shared counter above, an atomic update or a short protected section can prevent a lost update; pausing interrupts for longer increases response delay. The three strategies make different tradeoffs:

The short-handler strategy can be combined with a brief protected copy-and-clear in the loop. That combines strategies two and three: defer the processing, but protect the shared handoff. Part 2 develops the interrupt example.

← Back to the chapter · Previous detail · Next detail →