Simvik

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=0

Called 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=1

Learn it first

More Timing, interrupts and concurrency problems