Protect a shared variable
Make a read-modify-write safe from interrupts, and safe to nest. A medium embedded C problem (Timing, interrupts and concurrency), run and graded in the…
medium · Timing, interrupts and concurrency · interrupts · critical-section · atomicity
Adding to a variable takes a read, an add and a write. If an interrupt changes the variable between the read and the write, its update is lost.
Add amount to the shared variable with interrupts disabled for the whole read-modify-write. Afterwards, restore the interrupt state to exactly what it was before the call: if the caller already had interrupts disabled, they must stay disabled.
Starter code
void counter_add(uint32_t amount) {
// Not safe: an interrupt can run between the read and the write.
shared_write(shared_read() + amount);
}Example tests
Interrupts are off during the update and back on afterwards
shared = 5;
counter_add(3);
printf("value=%u unprotected=%u irq_disabled=%u\n", shared, violations, primask);Expected output:
value=8 unprotected=0 irq_disabled=0Called with interrupts already disabled
primask = 1;
shared = 1;
counter_add(1);
printf("value=%u unprotected=%u irq_disabled=%u\n", shared, violations, primask);Expected output:
value=2 unprotected=0 irq_disabled=1Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Debounce a button · Accept a new button state only after it has been stable for several samples.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Driver: measure worst-case time with the cycle counter · Enable the Cortex-M cycle counter and time a function across many runs, wraparound included.
- Smart lock: relock after 30 seconds · Relock automatically, with time arithmetic that survives the millisecond counter wrapping.