Is INC on a memory operand atomic on x86, and what about counter++ on ARM Cortex-M?

ARM is a load/store architecture with no instruction that modifies memory in place, so counter++ is always LDR, ADDS, STR, and an interrupt can arrive between any two of them. If the handler increments the same variable in that window, its update is overwritten when the main code executes its STR.

Cortex-M3, M4 and M7 provide exclusive-access instructions for this: ldrex r1, [r0], adds r1, #1, strex r2, r1, [r0], cmp r2, #0, bne retry. STREX performs the store only if the exclusive monitor is still set and writes 0 to r2 on success or 1 on failure. Taking an exception clears the monitor, so an interrupt in the middle makes the store fail and the loop retries with a fresh value.

Read more here: Source link