Reordering atomic operations in C ++

Suppose I have 2 threads:

int value = 0;
std::atomic<bool> ready = false;

thread 1:
value = 1
ready = true;

thread 2:
while (!ready);
std::cout << value;

Can this program output 0?

I read about the C ++ memory model - in particular, consistent consistency, which, in my opinion, is defaulted, and that was not particularly clear. Does the compiler only need to place atomic operations in the correct order relative to each other or require atomic operations to be in the correct order relative to all other operations?

+7
source share
5 answers

memory_order_seq_cst, , .

, : value = 1 : value = 1, std::cout << value; 1.

std::cout << value;
: while (!ready);.

+6

ShadowRanger. , , , Herb Sutter . , .

+1

   0?

.

. ISO C++ seq_cst acq_rel , , UB.

: , true. value - , true. , .


asm ISA . - , UB , .

0

, , .

Cst , ; . , , .

, . , , , , , .

C++ .

-1

: - C C++ C C++, , - UB ( ), , . , C C++ ( ).

: ( , , UB).

, . while (!ready); , : "".

"" "" , : , , , , ( ) , , . , . , , .

Thanks to multithreading, you can perform operations with memory that are not in the past of others , and you cannot know what they will observe if they try to use objects that are manipulated in the past.

-2
source

Source: https://habr.com/ru/post/1659267/


All Articles