What is the logic of Volatile.Read and Volatile.Write?

From MSDN Volatile.Read():

Reads a field value. On systems that require this, a memory barrier is inserted that prevents the processor from reordering the following operations: If reading or writing code appears after this method, the processor cannot move it before this method.

and Volatile.Write():

Writes a value to a field. On systems that require this, a memory barrier is inserted that prevents the processor from reordering the following operations: if a reading appears before this method or writing to the code, the processor cannot move it after this method.

I think I can understand the use cases Volatile.Read()and Volatile.Write(), and I saw many examples explaining why these two methods help to ensure the correctness of the program.

But I still wonder what the logic of these rules is.

Take, Volatile.Read()as an example, why it requires operations after , it cannot be moved before , but does not require anything from operations before that?

And why is it the opposite Volatile.Write()?

Thank!

+4
source share
2 answers

, volatile write, , - , , , - , .

, , Thread1 A, volatile write to a flag, , . , A, . , " " flag, , , , .

, Thread2 . , flag get set, A . , , , , Thread2 A, , .

: , Thread1 , flag, , , , Thread2 , Thread2 .

, . ?

, , Thread2, , , A , , Thread1 , , A. , Thread2 , A, , Thread1 , flag , Thread2 , .

+3

.
.NET (. ECMA-335), , , jit cpu ( ) .
/jit/cpu - , :

CLI , , , , , , CIL. ( ) . ( , , .)

, , .
,

(System.Threading.Monitor.Enter ) (System.Threading.Monitor.Exit ), .

, - ( ) ( Volatile.Read ), ( Volatile.Write ). , , .

+2

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


All Articles