以下是 C++ 中单例模式的一个众所周知的实现。
但是,我不完全确定它是否是线程安全的。
根据之前对类似问题的回答,它似乎是线程安全的。
是这样吗?
//Curiously Recurring Template Pattern
//Separates a class from its Singleton-ness (almost).
#include <iostream>
using namespace std;
template<class T> class Singleton {
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T& instance() {
static T theInstance;
return theInstance;
}
};
// A sample class to be made into a Singleton
class MyClass : public Singleton<MyClass> {
int x;
protected:
friend class Singleton<MyClass>;
MyClass() { x = 0; }
public:
void setValue(int n) { x = n; }
int getValue() const { return x; }
};
不,这不是线程安全的,因为静态局部不受任何方式的保护。默认情况下,静态局部变量不是线程安全的。这意味着您可能会遇到以下问题
- 单例的构造函数运行多次
- 对静态的分配不能保证是原子的,因此您可以在多线程场景中看到部分分配
- 可能还有一些我还缺少的。
这是 Raymond Chen 撰写的详细博客文章,介绍了为什么 C++ 静态默认情况下不是线程安全的。
- http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)