When should I use volatile/Thread.MemoryBarrier() for thread safety?
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.