According to section 14.5.4 of the C# language spec (ECMA 334, 6th Edition), volatile fields are all about preventing reordering:
14.5.4 Volatile fields
When a field_declaration includes a volatile modifier, the fields introduced by that declaration are volatile fields. For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock_statement (§12.13). These optimizations can be performed by the compiler, by the run-time system, or by hardware. For volatile fields, such reordering optimizations are restricted:
• A read of a volatile field is called a volatile read. A volatile read has “acquire semantics”; that is, it is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.
• A write of a volatile field is called a volatile write. A volatile write has “release semantics”; that is, it is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.
This is in contrast with the Java memory model, which also provides visibility guarantees (link):
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable
In the same section, the C# spec also contains the snippet below which shows how a volatile write is used to ensure that the main thread correctly prints result = 143
:
class Test
{
public static int result;
public static volatile bool finished;
static void Thread2()
{
result = 143;
finished = true;
}
static void Main()
{
finished = false;
new Thread(new ThreadStart(Thread2)).Start();
for (;;)
{
if (finished)
{
Console.WriteLine($"result = {result}");
return;
}
}
}
}
However, there's no mention of what guarantees the (eventual?) visibility of the write to finished
. Is this just implicit, or is it covered elsewhere in the spec?