有人能确认一下这是否是一个线程安全的单例实现吗?
can some one confirm if this is a thread safe implementation of singleton
#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;
你的实现似乎是线程安全的,但最简单的方法,使一个线程安全的单例看起来像
class Singleton {
Singleton();
public:
~Singleton() {
}
static Singleton* getInstance() {
static Singleton theInstance;
return &theInstance;
}
};
或者最好返回一个引用
static Singleton& getInstance() {
static Singleton theInstance;
return theInstance;
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 在std::thread中,joinable()然后join()线程安全吗
- 在c++队列中使用pop和visit实现线程安全
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 全局变量 多读取器 一个写入器多线程安全?
- 共享队列的线程安全
- boost::文件系统::recursive_directory_iterator多线程安全
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 以线程安全的方式转换 C/C++ 中时区名称字符串的时区偏移量
- 线程安全运算符<<
- 如何使缓存线程安全
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 提升精神 V2 Qi 语法线程安全吗?
- 线程调用的函数对对象删除是否安全?
- asio 链对象线程安全吗?
- 线程安全队列 c++
- 提供对不同类型的数据(建议、代码审查)的线程安全访问的类
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具