有人可以确认这是否是单例的线程安全实现 [英] can some one confirm if this is a thread safe implementation of singleton

查看: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;

推荐答案

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

Your implementation seems to be thread safe, but the simplest way to make a thread safe singleton looks like

class Singleton {
    Singleton();

public:
    ~Singleton() {
    }

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

或者更好地返回一个引用

or better return a reference

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

您无需在这里重新发明轮子.

You don't need to reinvent the wheel here.

这篇关于有人可以确认这是否是单例的线程安全实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆