I read this article about volatile fields in C #.
using System;
using System.Threading;
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 = {0}", result);
return;
}
}
}
}
As you can see, there is a loop in the main thread waiting to set the volatile flag to print the “result”, which is assigned 143 before the flag is set. The explanation says that if the flag was not declared as volatie, then
it is permissible for the store to be visible to the main stream after the store shuts down
Did I miss something? Even if it wasn’t volatile, how did it happen that the program would ever be printed 0.
source
share