I was reading the following article: http://msdn.microsoft.com/en-us/magazine/cc817398.aspx "Solving 11 Likely Problems In Your Multithreaded Code" by Joe Duffy
And it raised me a question: "We need to lock a .NET Int32 when reading it in a multithreaded code?"
我理解如果在32位操作系统中使用Int64可能会分裂,就像文章中解释的那样。但是对于Int32,我想象了以下情况:
class Test
{
private int example = 0;
private Object thisLock = new Object();
public void Add(int another)
{
lock(thisLock)
{
example += another;
}
}
public int Read()
{
return example;
}
}
我认为在Read方法中包含一个锁的原因不充分。你认为呢?
根据Jon Skeet和ctacke的回答,我理解上面的代码仍然容易受到多处理器缓存的影响(每个处理器都有自己的缓存,与其他处理器不同步)。以下的三个修改都解决了这个问题:
- Adding to "int example" the "volatile" property
- Inserting a Thread.MemoryBarrier(); before the actual reading of "int example"
- Read "int example" inside a "lock(thisLock)"
我认为“易挥发”(volatile)是最优雅的解决方案。