What is Read-modify-write?
A sequence that reads a value, changes part of it and writes it back. If interrupted midway, other changes can be lost.
Japanese name: 読み出し・変更・書き込み
A sequence that reads a value, changes part of it and writes it back. If interrupted midway, other changes can be lost.
Japanese name: 読み出し・変更・書き込み
A statement that sets one bit of a register, such as PORT |= (1 << 3), runs as three steps: read the value, modify the bit, write it back. If an interrupt arrives between the read and the write and its handler changes another bit of the same register, the write-back overwrites that change with the old value. The bug appears only occasionally and is hard to reproduce.
The basic method is to disable interrupts for the duration of the operation. Some microcontrollers have dedicated registers that set or clear only the bits written to them, so no read is needed and an interruption does no harm (BSRR on STM32, for example). On AVR, bit operations on some I/O registers compile to a single instruction (sbi, cbi). For variables, the language or the CPU can provide operations that cannot be interrupted (C11 atomic types, exclusive load and store instructions).
In registers whose bits are cleared by writing 1, such as interrupt flags, using |= writes 1 to every flag that was set when the register was read and clears causes that have not been handled yet. Write 1 only to the bit to be cleared. On microcontrollers where reading an I/O port returns the actual pin voltage instead of the output setting, a pin whose voltage has not risen fully under load reads as 0, and the write-back changes the output. Using the LAT registers on PIC avoids this.
Answer: A. The handler's change is lost when main writes back; disable interrupts during the update or use dedicated per-bit set/clear registers
"reg |= mask" is three operations: read the register, OR, and write back. If an interrupt arrives right after the read and the handler changes another bit, main writes back a value based on the stale read, wiping out the handler's change. Disabling interrupts during the operation, or using set and clear registers where only the bits written as 1 change, makes it a single write and avoids the problem.
No. volatile only stops the compiler from removing or reordering the reads and writes. It does not stop an interrupt from arriving between the read and the write.
Disabling interrupts is not enough because the other cores keep running. Use mutual exclusion such as a spinlock, or atomic operations.
Building real circuits is a good way to check what you learned in the questions.
As an Amazon Associate I earn from qualifying purchases.
This page was drafted with AI and fact-checked by a separate AI review before publication. Our Editorial policy explains how we write and check content. If you spot an error, please tell us on our Contact page.