The volatile keyword in C # refers to read / write reordering, so this is something rather esoteric.
http://www.albahari.com/threading/part4.aspx#_Memory_Barriers_and_Volatility
(which I consider one of the "bibles" about streaming processing) writes:
The volatile keyword instructs the compiler to generate a binding for each reading from this field and a lock for each record in this field. The fence-fence prevents the movement of other readings / records before the fence; The shutter fence prevents the movement of other reads / records after the fence. These midfielders are faster than full fences because they give lead time and equipment more room for optimization.
This is something completely unreadable :-)
Now ... What does this not mean:
- This does not mean that the value will be read now / will be written now
it just means that if you read something from a mutable variable, everything else that was read / written before this βspecialβ read will not be moved after that βspecialβ read. Therefore, it creates a barrier. It is ironic that by reading from a mutable variable, you guarantee that all the records that you made with any other variable (volatile or not) at the reading point will be executed.
Volatile recording is something more important, and it is partially guaranteed by the Intel processor, and what was not guaranteed by the first version of Java: there is no reordering of the recording. The problem was this:
object myrefthatissharedwithotherthreads = new MyClass(5);
Where
class MyClass { public int Value; MyClass(int value) { Value = value; } }
Now ... this expression can be represented as:
var temp = new MyClass(); temp.Value = 5; myrefthatissharedwithotherthreads = temp;
where temp is something generated by the compiler that you don't see.
If the entries can be reordered, you can:
var temp = new MyClass(); myrefthatissharedwithotherthreads = temp; temp.Value = 5;
and another thread could see the partially initialized MyClass , because the value of myrefthatissharedwithotherthreads can be read before the initialization of the MyClass class is complete.