Skip to main content
 首页 » 编程设计

c#之使用内存屏障

2024年02月24日17dflying

在下面的代码示例中,是否需要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.