Search code examples
c++multithreadingc++11memory-modeldata-race

Does re-writing the same value to a memory location count as modifying the memory? (in the context of multi-threading)


(Assume: int x{ 6 } and 2 evaluations write x = 6 at the same time)

--

CPP reference says on Multi-threaded executions and data races | Data races:

When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race unless:

  • both evaluations execute on the same thread or in the same signal handler, or

  • both conflicting evaluations are atomic operations (see std::atomic), or

  • one of the conflicting evaluations happens-before another (see std::memory_order).

If a data race occurs, the behavior of the program is undefined.

The reference says: "an evaluation of an expression writes" / "another evaluation reads or modifies".

(Assume that both evaluations are equal) Does writing the same value to a memory location count as modifying the memory?

--

UPDATE:

C++ standard says on 6.9.2.2 Data races:

  1. Two expression evaluations conflict if one of them modifies a memory location ([intro.memory]) and the other one reads or modifies the same memory location.

Based on the C++ standard, I fixed the paragraph in the reference. Now it says modifies instead of writes.


Solution

  • Does writing the same value to a memory location count as modifying the memory?

    Yes, for example simple assignment to a scalar object (which is what a memory location actually is with exceptions for bit fields) is defined to modify the object regardless of the value that the object is being changed to. See [expr.ass]/2:

    1. In simple assignment (=), the object referred to by the left operand is modified ([defns.access]) by replacing its value with the result of the right operand.

    You find similar wording for all other expressions that affect the value of a scalar object.


    Regarding terminology, the standard usually doesn't use "write", it uses "modify" with the same meaning instead. See e.g. [defns.access].