Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it's termed read-modify-write but not read-write?

In my opinion, the term read-modify-write doesn't make much sense, since modify is just another way of saying write. Quoted from wikipedia (emphasis mine):

In computer science, read-modify-write is a class of atomic operations [...] that both read a memory location and write a new value into it simultaneously [...]

So why not simply read-write? Any delicate semantic difference between the two?

like image 337
Lingxi Avatar asked Dec 14 '22 17:12

Lingxi


1 Answers

Why it's termed read-modify-write but not read-write?

Because that is exactly the sequence of events on a typical architecture such as X86.

  1. read: The value is read from a memory location (cache) into a CPU register
  2. modify: The value is incremented inside the CPU register
  3. write: The updated register value is written back to memory (cache).

In order to create the perception of atomicity, the cache line is locked between the read and the write operation.

For example, incrementing a C++ atomic variable:

g.fetch_add(1);

Is compiled by gcc into:

0x00000000004006c0 <+0>:     lock addl $0x1,0x200978(%rip)        # 0x601040 <g>

Despite being a single instruction, addl is not atomic by itself. The lock prefix is necessary to guarantee that the updated register value is written back to the cache line before it can be accessed by other cores (the store buffer is flushed, but bypassed for RMW operations).

The MESI cache coherence protocol ensures that all cores observe the updated memory value after the lock on the cache line has been released. This guarantees that all threads observe the latest value in the modification order which is required for RMW operations by the C++ standard.

like image 136
LWimsey Avatar answered Jan 03 '23 12:01

LWimsey