支持多线程的单例类
singleton.h:
#ifndef _SINGLETON_H
#define _SINGLETON_H
#include "lock.h"
template<class type>
class Singleton : public NonCopy
{
public:
Singleton() : instance_(NULL) {
}
~Singleton() {
if (instance_ != NULL) {
delete instance_;
instance_ = NULL;
}
}
type *Get() {
if (instance_ == NULL) {
ScopeLock scope_lock(&lock_);
if (instance_ == NULL) {
type *temp = new type;
instance_ = temp;
}
}
return instance_;
}
type &operator*() {
return *Get();
}
type *operator->() {
return Get();
}
private:
SpinLock lock_;
type *volatile instance_;
};
#endif // _SINGLETON_H
singleton.cpp
#include "singleton.h"
class Test{
public: void print() {
cout << "test" << endl;
}
static Test* GetInstance() {
static Singleton<Test> test;
return test.Get();
}
};
int main()
{
Test::GetInstance()->print();
return 0;
}
编译:g++ -o singleton singleton.cpp lock.cpp -lpthread