... continued

Continues the discussion on the volatile concept.

We'll cover the following...

Before we end the discussion on volatile, let's discuss some more examples often quoted to demonstrate the difficulty of correctly reasoning and applying the volatile keyword.

Consider the following example:

Press + to interact
class ReorderingExample
{
private int ping = 0;
private int pong = 0;
private volatile int foo = 0;
private volatile int bar = 0;
public void reorderTest()
{
Thread t1 = new Thread(() =>
{
foo = 1;
ping = bar;
});
Thread t2 = new Thread(() =>
{
bar = 1;
pong = foo;
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine(ping + " " + pong);
}
}

We have two volatile fields and two ordinary fields. The first thread executes the following two instructions: ...