C Programming · Interview question

Is reg |= (1u << n) safe to use on a register that an interrupt also modifies?

A strong answer

No, reg |= mask is not atomic. It compiles to a read-modify-write: load the register into a CPU register, OR in the bit, store it back. If an interrupt fires between the load and the store and modifies the same register, the ISR's change is sitting in the register when the interrupted code stores its stale-plus-modified value back, wiping the ISR's update. This is a classic data race. Mitigations: disable interrupts around the RMW (a critical section), use the hardware's atomic bit-set/bit-clear registers if the MCU provides them (e.g. STM32's BSRR, which sets or clears pins in a single write with no read), or use atomic intrinsics. Marking the variable volatile does not fix this, volatile guarantees the accesses happen but does nothing about atomicity of the read-modify-write sequence.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Bit Manipulation & Masks

Set, clear, toggle, and test individual bits without disturbing their neighbors: the read-modify-write idioms behind every GPIO and peripheral driver.

More Bit Manipulation & Masks questions

Browse all 472 interview questions
Is reg |= (1u << n) safe to use on a register that an interrupt also modifies? | EmbeddedPrep.io