简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM