Read-modify-write

From Wikipedia, the free encyclopedia

In computer science, read-modify-write is a sequence of instructions that reads a value from a memory address, modifies the value that was read, and then writes the modified value back to the memory address.

Here is example C code for explicit read-modify-write. Assume x is an in-memory int variable.

    register int r;
    r = x;
    r = r + 1;
    x = r;

Read-modify-write can be less obvious, though. The following C code produces equivalent read-modify-write on many CPUs.

    ++x;

(Both examples likely produce very similar object code when compiled.)

In a system with interrupts or preemptive scheduling, it's possible for the sequence to be interrupted between the read and the write. If an interrupt service routine or another thread accesses the same memory (e.g., the variable x in the examples), a critical section should be used to prevent a race condition.