Blocking lock includes a memory intake at the beginning and at the end (beginning and end of the block). This ensures that any changes in memory will be visible to other kernels (for example, other threads running on other kernels). In your example, changes in x, y, z in your first block block will be visible to any other threads. โVisibleโ means that any values โโstored in the register will be flushed to memory, and any memory cached in the CPU cache will be flushed to physical memory. ECMA 334 indicates that the blocking block is a block surrounded by Monitor.Enter and Monitor.Exit. In addition, ECMA 335 states in detail that Monitor.Enter "implicitly performs a volatile read operation ..." and "Monitor.Exit" implicitly performs a volatile write operation. This means that modifications will not be visible to other kernels / threads until the end of the blocking block (after Monitor.Exit), but if all your access to these variables is protected by a lock, in any case, simultaneous access to the specified variables in different kernels / there will be no flows.
This actually means that any variables protected by the lock statement do not have to be declared mutable so that their changes are visible to other threads.
Since the sample code contains only an operation that relies on one general atomic operation (reading and writing a single value in y), you can get the same results:
try { x = 10; y = 20; Thread.VolatileWrite(ref z, a + 10); }
and
if(y == 10) {
The first block guarantees that the entry in x will be visible before the entry in y, and the entry in y will be visible before the entry in z. It also ensures that if entries in x or y were cached in the CPU cache, that cache would be flushed to physical memory (and thus visible to any other thread) immediately after the call to VolatileWrite.
If in the if(y == 10) block if(y == 10) you are doing something with x and y , you should return to using the lock keyword.
In addition, the following would be identical:
try { x = 10; y = 20; Thread.MemoryBarrier(); z = a + 10; }
source share