Search⌘ K
AI Features

... continued

Explore the volatile keyword's role in C# concurrency, focusing on how instruction reordering and memory optimizations impact volatile fields. Learn why volatile alone does not prevent compiler hoisting and how to manage loop polling with memory barriers to ensure correct multithreaded behavior.

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:

C#
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: ...