Created
December 27, 2016 11:23
-
-
Save typhoonzero/0dcfb61dc9c0a3e167d71465e6c6bf41 to your computer and use it in GitHub Desktop.
A thread safe base template class of c++ Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <iostream> | |
#include <pthread.h> | |
#ifndef SINGLETON_H | |
#define SINGLETON_H | |
namespace util { | |
template <class T> | |
class Singleton { | |
public: | |
static pthread_rwlock_t rwlock; | |
Singleton(){ | |
}; | |
static T* GetInstance() { | |
pthread_rwlock_rdlock(&rwlock); | |
if (!_instance) { | |
pthread_rwlock_unlock(&rwlock); | |
pthread_rwlock_wrlock(&rwlock); | |
if (!_instance) { | |
_instance = new T; | |
_instance->Init(); | |
} | |
} | |
pthread_rwlock_unlock(&rwlock); | |
return _instance; | |
}; | |
virtual ~Singleton() {}; | |
virtual void Init() = 0; | |
static void Destroy() { | |
pthread_rwlock_rdlock(&rwlock); | |
if (_instance) { | |
pthread_rwlock_unlock(&rwlock); | |
pthread_rwlock_wrlock(&rwlock); | |
if (_instance) { | |
delete _instance; | |
_instance = NULL; | |
} | |
} | |
pthread_rwlock_unlock(&rwlock); | |
} | |
private: | |
static T* _instance; | |
Singleton(Singleton const &s); | |
Singleton & operator = (const Singleton &); | |
}; | |
template<class T> | |
T* Singleton<T>::_instance = NULL; | |
template<class T> | |
pthread_rwlock_t Singleton<T>::rwlock = PTHREAD_RWLOCK_INITIALIZER; | |
} // namespace util | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can inherent it and realize real jobs.