【问题标题】:How to write a thread-save singliton using C++11如何使用 C++11 编写线程安全的单例
【发布时间】:2022-09-23 15:56:39
【问题描述】:

我不确定这是否是线程安全的:

#include <thread>
#include <stdio.h>

class A {
public:
  static A* instance() {
      static A* ptr = new A();
      return ptr;
  }

  int val_;
};

int main(int argc, char *argv[]) {
  auto ptr = A::instance();
  printf(\"thread value: %d\\n\", ptr->val_);
  //thd1.join();
  return 0;
}

C++ 代码和 ARM 程序集:https://godbolt.org/z/aPYarcoM9

我明白了保护变量确保静态变量只初始化一次,并且守卫获取/释放锁定A类的建设。

我不确定以下是线程安全的吗?

auto ptr = A::instance();

    标签: c++11 thread-safety singleton


    【解决方案1】:

    小心那个双重检查
    实例 == nullptr

    class Singleton
    {
    public:
        Singleton *getInstance()
        {
            if (instance == nullptr)
            {
                unique_lock<mutex> lock(m_mutex);
                if (instance == nullptr)
                    instance = new Singleton();
            }
            return instance;
        }
    
    private:
        Singleton() {}
        ~Singleton() {}
    
        static Singleton *instance;
        static mutex m_mutex;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多