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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With