C# - Volatile Fields
Track/Stream: Moloko - Fun For Me
Fields in C# classes can be marked as volatile. I'm slightly unclear on this, but it looks like a niche task, really only needed for concurrent thread signalling issues. For example, if you have the following:
class Foo
{
public int i = 0;
public bool b = false;
public void Go()
{
i = 42;
b = true;
}
public int Wait()
{
while (!b)
System.Threading.Thread.Sleep(1);
return i;
}
}
If you call Go() from thread A, then call Wait() from thread B, it's possible to get 0 as your result. This is because .NET optimizes stuff behind the scenes, and assignment statements might not get executed in order behind the scenes. This is all covered when you're using a single thread (so if thread A checked these values, it'd be fine), but for multithreaded scenarios it isn't handled.
Now, if you were to put a volatile keyword on b (i.e. public volatile bool b; ), it would ensure that all assignments were flushed before b is assigned.
I'm sure there's an excellent reason behind this, but I'm equally sure I've pebcak'ed a bug or two due to this. Hmmmm, one more thing to watch out for.
0 Comments:
Post a Comment