I would like to code a little program which visually illustrates the behavior of the volatile
keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that.
Adding the volatile keyword in the same program should fix the problem.
That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword.
Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?
I've achieved a working example!
The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one:
If you run this example in Release mode and without debugger (i.e. using Ctrl+F5) then the line while (test.foo != 255)
will be optimized to 'while(true)' and this program never returns.
But after adding volatile
keyword, you always get 'OK'.
class Test
{
/*volatile*/ int foo;
static void Main()
{
var test = new Test();
new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();
while (test.foo != 255) ;
Console.WriteLine("OK");
}
}