Gun
Gun

Reputation: 1411

What is the volatile keyword purpose in c#?

I want to see the real time use of Volatile keyword in c#. but am unable to project the best example. the below sample code works without Volatile keyword how can it possible?

class Program
{
    private static int a = 0, b = 0;

    static void Main(string[] args)
    {
        Thread t1 = new Thread(Method1);
        Thread t2 = new Thread(Method2);

        t1.Start();
        t2.Start();

        Console.ReadLine();
    }

    static void Method1()
    {
        a = 5;
        b = 1;
    }

    static void Method2()
    {
        if (b == 1)
            Console.WriteLine(a);
    }
}

In the above code i am getting a value as 5. how it works without using volatile keyword?

Upvotes: 6

Views: 246

Answers (2)

Guffa
Guffa

Reputation: 700152

The volatile keyword tells the compiler that a variable can change at any time, so it shouldn't optimise away reading and writing of the variable.

Consider code like this:

int sum;
for (var i = 0; i < 1000; i++) {
  sum += x * i;
}

As the variable x doesn't change inside the loop, the compiler might read the variable once outside the loop and just use the same value throughout the loop.

If you make the variable x volatile, the compiler will read the value of the variable each time that it is used, so if you change the value in a different thread, the new value will be used immediately.

Upvotes: 11

David Schwartz
David Schwartz

Reputation: 182753

If you use volatile properly, your code is guaranteed to work. If you leave out volatile where your code requires it, it will probably work fine most of the time, but it is not guaranteed and will probably fail when it will hurt the most.

Understanding how code with threading races fails or doesn't fail requires a deep understanding of the implementation and the platform. It's not simple and usually not worth worrying about. Just follow the rules and your code will work all the time.

Upvotes: 2

Related Questions