代码之家  ›  专栏  ›  技术社区  ›  ricky

在c++中使用带内存屏障的双重检查锁定时,正确的方法是什么?

  •  1
  • ricky  · 技术社区  · 7 年前

    C++ and the Perils of Double-Checked Locking

    我不明白为什么我们必须使用示例12中的第一个内存屏障(如下所示):

    Singleton* Singleton::instance () {
           Singleton* tmp = pInstance;
           ... // insert memory barrier
           if (tmp == 0) {
              Lock lock;
              tmp = pInstance;
              if (tmp == 0) {
                 tmp = new Singleton;
                 ... // insert memory barrier
                 pInstance = tmp;
              }
           }
           return tmp;
        }
    

    Singleton* Singleton::instance () {
           if (pInstance == 0) {
              Lock lock;
              if (pInstance == 0) {
                 Singleton* tmp = new Singleton;
                 ... // insert memory barrier
                 pInstance = tmp;
              }
           }
           return pInstance;
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   1201ProgramAlarm    7 年前

    不,不安全。阅读示例前面的三段和后面的两段,潜在的问题是系统中的写入 pInstance Singleton 已刷新。然后线程A可以读取 ,将指针视为非null,并返回它,从而允许线程A访问 单子

    第一次刷新是必要的,以确保在构造 单子 之前 你试着在另一个线程中使用它。

    根据您运行的硬件,这可能不是问题。

    推荐文章