Is the explanation of relaxed ordering erroneous in cppreference?

后端 未结 3 1353
粉色の甜心
粉色の甜心 2021-02-07 15:03

In the documentation of std::memory_order on cppreference.com there is an example of relaxed ordering:

Relaxed ordering

Atomic operations tagged

3条回答
  •  再見小時候
    2021-02-07 15:45

    It is sometimes possible for an action to be ordered relative to two other sequences of actions, without implying any relative ordering of the actions in those sequences relative to each other.

    Suppose, for example, that one has the following three events:

    • store 1 to p1
    • load p2 into temp
    • store 2 to p3

    and the read of p2 is independently ordered after the write of p1 and before the write of p3, but there is no particular ordering in which both p1 and p3 partake. Depending upon what is done with p2, it may be impractical for a compiler to defer p1 past p3 and still achieve the required semantics with p2. Suppose, however, the compiler knew that the above code was part of a larger sequence:

    • store 1 to p2 [sequenced before the load of p2]
    • [do the above]
    • store 3 into p1 [sequenced after the other store to p1]

    In that case, it could determine that it could reorder the store to p1 after the above code and consolidate it with the following store, thus resulting in code that writes p3 without writing p1 first:

    • set temp to 1
    • store temp to p2
    • store 2 to p3
    • store 3 to p1

    Although it may seem that data dependencies would cause certain parts of sequencing relations to behave transitively, a compiler may identify situations where apparent data dependencies don't exist, and would thus not have the transitive effects one would expect.

提交回复
热议问题