Confused in atomic class: memory_order_relaxed

I am studying this site: https://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync , which is very useful for understanding the topic of the atomic class.

But this relaxed example is hard to understand:

    /*Thread 1:*/

    y.store (20, memory_order_relaxed)
    x.store (10, memory_order_relaxed)
    /*Thread 2*/
 if (x.load (memory_order_relaxed) == 10)
      {
        assert (y.load(memory_order_relaxed) == 20) /* assert A */
        y.store (10, memory_order_relaxed)
      }
 /*Thread 3*/
     if (y.load (memory_order_relaxed) == 10)
        assert (x.load(memory_order_relaxed) == 10) /* assert B */

For me, statement B should never fail, since x must be 10 and y = 10 due to the fact that thread 2 is due to this.

But the website says that either the statement in this example can actually CORRECT.

+6
source share
3 answers

, , . , ++, , , .

, , , . , ( ), .

: . .

CPU , , , .

, , , sorta . , , "". , - , .

, , , ++ : , . .

, , . - . .

, memory_order_relaxed? , , (, , ). , "" ,

  • 1 20 y, 10 - x .
  • 2 10 y.
  • Thread 3 1, 2, .

, , .

, . .

- std::mutex, .

+1

B , x 10 y = 10 - , 2 .

, , , 2 10 x 10 y, 3 .

, , , , . 2 10 x 10 y, 3 .

, B , , , , 3 10 y, , , 10 y . 10 y 10 y. , , :

// thread 2
y.store (10, memory_order_release);

// thread 3
if (y.load (memory_order_acquire) == 10)

, . , 2 ​​ 3, , 3, , 2. , .

, , A , x.store 1, release, x.load 2.

+4

- ++.

[intro.races] ( : ).

, , . , ++, [intro.multithread] . , (), !

[intro.races]/4:

M , . [: . , . , , . - ]

. , memory_order_seq_cst, [atomics.order]/3:

memory_order_seq_cst S, " " [...]

+1

All Articles