c# - 使用内存屏障

标签 c# multithreading lock-free memory-model

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

相关文章:

c# - Queue.Synchronized 比使用 Lock() 更快吗?

c++ - par_unseq 和 "vectorization-unsafe"函数

c# - WinForms 打印到默认打印机,即使它不可用/连接

c# - 锁定并完成所有工作,还是仅在必要时松开并抓取?

c# - 如何在 C# 中实现与在 Java 中相同的覆盖体验?

c++ - 从工作线程在主线程中运行一些代码

c# - 使用 JSON.net 将内部数组反序列化为对象

c++ - 检测 "new"项目何时被删除

multithreading - 使用 boost::lockfree::spsc_queue 时需要内存屏障吗?

c++ - C++中的无锁堆栈弹出式实现