MaPi
MaPi

Reputation: 1601

Using Volatile keyword in C#

I am using the Volatile keyword, but it is behaving someway different than expected.

Here's my code

private static volatile int _N = 0;



var up = Task.Run(() =>
{
    for (int i = 0; i < 1000000; i++)
        _N++;
});
for (int i = 0; i < 1000000; i++)
    _N--;
up.Wait();
Console.WriteLine(_N);

_N is a class variable.

What I get is a different number every time, as if the keyword volatile were not used. Is it the right behaviour of the keyword?

Upvotes: 1

Views: 383

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499860

What I get is a different number every time, as if the keyword volatile were not used. Is it the right behaviour of the keyword?

Specifying the variable as volatile doesn't make either the increment or decrement operation atomic. Imagine that your loop had been written like this:

for (int i = 0; i < 1000000; i++)
{
    int x = _N;
    x++;
    _N = x;
}

That's effectively what the previous loop was - it's just that now it's clearer that you're reading, then performing an operation, then writing. There's nothing to stop another thread from writing a different value between those two operations.

For atomicity, you should use Interlocked.Increment and Interlocked.Decrement.

Personally I would try to avoid using volatile wherever possible. The exact meaning of it is relatively hard to describe, and hard to reason about in my view. It's better to use higher level constructs where possible.

Upvotes: 11

Related Questions