在下面的代码示例中,是否需要FuncA 中的内存屏障来确保读取最新的值?
class Foo
{
DateTime m_bar;
void FuncA() // invoked by thread X
{
Thread.MemoryBarrier(); // is required?
Console.WriteLine(m_bar);
}
void FuncB() // invoked by thread Y
{
m_bar = DateTime.Now;
}
}
编辑:如果不是,我如何确保 FuncA 读取最新值? (我想确保最近的值实际上存储在处理器的缓存中)[不使用锁]
最佳答案
对我来说,这就像一个大大的“不”。 Thread.MemoryBarrier() 仅同步实现它的线程内的内存访问。
来自 MSDN:
The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
关于c# - 使用内存屏障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1731499/