When should I use volatile/Thread.MemoryBarrier() for thread safety?
You use volatile
/Thread.MemoryBarrier()
when you want to access a variable across threads without locking.
Variables that are atomic, like an int
for example, are always read and written whole at once. That means that you will never get half of the value before another thread changes it and the other half after it has changed. Because of that you can safely read and write the value in different threads without syncronising.
However, the compiler may optimize away some reads and writes, which you prevent with the volatile
keyword. If you for example have a loop like this:
sum = 0;
foreach (int value in list) {
sum += value;
}
The compiler may actually do the calculations in a processor register and only write the value to the sum
variable after the loop. If you make the sum
variable volatile
, the compiler will generate code that reads and writes the variable for every change, so that it's value is up to date throughout the loop.
What's wrong with
private static readonly object syncObj = new object();
private static int counter;
public static int NextValue()
{
lock (syncObj)
{
return counter++;
}
}
?
This does all necessary locking, memory barriers, etc. for you. It's well understood and more readable than any custom synchronization code based on volatile
and Thread.MemoryBarrier()
.
EDIT
I can't think of a scenario in which I'd use volatile
or Thread.MemoryBarrier()
. For example
private static volatile int counter;
public static int NextValue()
{
return counter++;
}
is not equivalent to the code above and is not thread-safe (volatile
doesn't make ++
magically become thread-safe).
In a case like this:
private static volatile bool done;
void Thread1()
{
while (!done)
{
// do work
}
}
void Thread2()
{
// do work
done = true;
}
(which should work) I'd use a ManualResetEvent to signal when Thread2 is done.
Basically if you're using any other kind of synchronization to make your code threadsafe then you don't need to.
Most of the lock mechanisms (including lock) automatically imply a memory barrier so that multiple processor can get the correct information.
Volatile and MemoryBarrier are mostly used in lock free scenarios where you're trying to avoid the performance penalty of locking.
Edit: You should read this article by Joe Duffy about the CLR 2.0 memory model, it clarifies a lot of things (if you're really interested you should read ALL the article from Joe Duffie who is by large the most expert person in parallelism in .NET)
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