本文介绍了有人可以确认这是否是单例的线程安全实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送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:关键词]
发布评论