Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 346
Gun Avatar asked Dec 03 '12 12:12

Gun


People also ask

What is the purpose of a volatile variable?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.

When should I use volatile in C?

Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.

What is volatile variable in C where it is used?

The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time. These are some properties of volatile. The volatile keyword cannot remove the memory assignment. It cannot cache the variables in register.


1 Answers

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.

like image 140
Guffa Avatar answered Sep 21 '22 11:09

Guffa