Jump to content

Read–modify–write

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Losat (talk | contribs) at 15:58, 16 June 2006. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

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.