Skip to content

Instantly share code, notes, and snippets.

@typhoonzero
Created December 27, 2016 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typhoonzero/0dcfb61dc9c0a3e167d71465e6c6bf41 to your computer and use it in GitHub Desktop.
Save typhoonzero/0dcfb61dc9c0a3e167d71465e6c6bf41 to your computer and use it in GitHub Desktop.
A thread safe base template class of c++ Singleton
#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
@typhoonzero
Copy link
Author

You can inherent it and realize real jobs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment