【问题标题】:can some one confirm if this is a thread safe implementation of singleton有人可以确认这是否是单例的线程安全实现
【发布时间】:2018-01-10 11:47:30
【问题描述】:
#include "iostream"
#include "atomic"

using namespace std;

class Singleton
{
    Singleton();


    static Singleton * _pInstance;

    public:
       ~Singleton() {
       }

       static Singleton* getInstance() {

          Singleton * tmp = _pInstance;

          atomic_thread_fence(std::memory_order_acquire);

          if (tmp == nullptr){

             tmp = _pInstance;

             if (!tmp) {

                _pInstance = new Singleton();

                atomic_thread_fence(std::memory_order_release);

                _pInstance = tmp;
             }

         return _pInstance;
     }
};

Singleton* Singleton::_pInstance = nullptr;

【问题讨论】:

  • 你能详细说明你的问题吗?
  • 我不知道这个,但是实现一个线程安全的单例是微不足道的。最简单的单例,即 Meyers 的单例,已经是线程安全的。
  • 双重检查锁定模式的危险:aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
  • 我尝试将 cmets 添加到代码中,但我不知道如何解决这个问题:请添加一些上下文来解释代码部分,我添加了 atomic_thread_fence 这样做好吗?跨度>
  • @HocineDJEMAI:您能否详细说明为什么要这样做而不是简单的线程安全实现。是研究吗?家庭作业?什么?

标签: c++ thread-safety singleton


【解决方案1】:

您的实现似乎是线程安全的,但制作线程安全单例的最简单方法看起来像

class Singleton {
    Singleton();

public:
    ~Singleton() {
    }

    static Singleton* getInstance() {
        static Singleton theInstance;
        return &theInstance;
    }
};

或者更好的返回参考

    static Singleton& getInstance() {
        static Singleton theInstance;
        return theInstance;
    }

你不需要在这里重新发明轮子。

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多