Monday, June 6, 2016

What is the use of volatile keyword?

Volatile keyword indicate that a variable may be modified by multiple thread. It always contain the most updated value. There is no need to use lock statement with volatile variable.

Volatile keyword states that a variable may be changed by multiple threads simultaneously. Variable contains most updated value by any thread. Value will be same for all thread.
There is no need to use lock with volatile field.
For nonvolatile variable, complier ensures that a variable accessed by one thread at a time.
Volatile keyword can be used with following types.
1.       Reference type.
2.       Type like sbyte,  byte, int, uint, short, ushort, float, bool,char
3.       Pointer Type, but pointer to volatile not possible.
4.       An enum type
Life without volatile.
class TestNonVolatile
{
    private bool _loop = true;

    public static void Main()
    {
        Test test1 = new Test();

        // Set _loop to false on another thread
        new Thread(() => { test1._loop = false;}).Start();

        // Poll the _loop field until it is set to false
        while (test1._loop == true) ;

        // The loop above will never terminate!
    }
}

Output:
Loop will never terminate.

There are two possible ways to get the while loop to terminate:
  1. Use a lock to protect all accesses (reads and writes) to the _loop field
  2. Mark the _loop field as volatile


When variable is declared volatile it essentially means that threads should not cache such a variable or in other words threads should not trust the values of these variables instead they are directly read from the main memory.


The volatile keyword states that a field may be modified by multiple threads which are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

No comments:

Followers

Link