有人可以确认这是否是单例的线程安全实现

编程入门 行业动态 更新时间:2024-10-25 14:30:38
本文介绍了有人可以确认这是否是单例的线程安全实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
#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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 16:27:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   线程   否是单例

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!