What I don’t understand about volatile and Memory-Barrier,

Loop raising erratic reading

I have read many places in which the volatile variable cannot be raised from a loop or if, but I cannot find mention of any places in the C # specification. Is this a hidden feature?

All entries are unstable in C #

Does this mean that all records have the same properties without as with the volatile keyword? For example, do regular entries in C # have release semantics? and all records flush the processor storage buffer?

Semantics release

Is this a formal way of saying that the processor's storage buffer is flushed when flying write?

Get semantics

Is this a formal way of saying that it should not load a variable into a register, but retrieve it from memory every time?

In this article , Igor talks about the "thread cache". I understand perfectly well that this is imaginary, but in fact he means:

  • Processor storage buffer
  • Loading variables into registers instead of collecting from memory every time
  • Some kind of processor cache (these are L1 and L2, etc.)

Or is it just my imagination?

Deferred entry

I have read many places that may be delayed. Is it due to reordering and storage buffer?

Memory barrier

I understand that a side effect is a call to "lock" or "when JIT converts IL to asm, and therefore Memory.Barrier can solve the delayed write to main memory (in the while loop) in fx this example:

static void Main()
{
  bool complete = false; 
  var t = new Thread (() =>
  {
    bool toggle = false;
    while (!complete) toggle = !toggle;
  });
  t.Start();
  Thread.Sleep (1000);
  complete = true;
  t.Join();        // Blocks indefinitely
}

? Memory.Barrier , ? , ​​ , - Memory.Barrier.

- Memory.Barrier?

+3
1

..

.


, volatile , - #. ?

MSDN : ", volatile, , ". , "" .


#

, , volatile? , # ? ?

. , . , .

CLR 2.0

2: , .. .

, , # (, , ), . ( # , 2):

, - : " .NET 2.0 - , ". (...) ECMA # , , .NET Framework (, , .NET Framework 4.5 ARM).


, ?

, . " ", store/load . , . .


, . - ?

. / , , .


, : .

. :

volatile # : , . / .

Microsoft # : , . OpCodes.Volatile, . .

, #, , .


bool complete = false; 
var t = new Thread (() =>
{
    bool toggle = false;
    while (!complete) toggle = !toggle;
});
t.Start();
Thread.Sleep(1000);
complete = true;
t.Join();     // blocks

? Memory.Barrier , ?

: , . ( ) .

: , / . # Thread.MemoryBarrier , , , .

. , ( Release ), , while. ? . :

if(complete) return;
toggle = !toggle;

if(complete) return;
toggle = !toggle;

if(complete) return;
toggle = !toggle;
...

complete volatile, , complete. , CLR (. 6) (!) . , :

if(complete) return;
toggle = !toggle;
toggle = !toggle;
toggle = !toggle;
...

, , .

toggle = !toggle, .

if(complete) return;
toggle = !toggle;
#FENCE
if(complete) return;
toggle = !toggle;
#FENCE
if(complete) return;
toggle = !toggle;
#FENCE
...

, , . , .

+11

All Articles