#ifndef SINGLETON_SINGLETON_H
#define SINGLETON_SINGLETON_H
#include <pthread.h>
class Singleton{
public :
static Singleton* getInstance ();
static void destroy();
private :
Singleton ();
~Singleton();
private :
static pthread_mutex_t mutex;
static Singleton* singleton_ptr;
};
#endif //SINGLETON_SINGLETON_H
#include <iostream>
#include "Singleton.h"
Singleton* Singleton::singleton_ptr= nullptr ;
pthread_mutex_t Singleton::mutex;
Singleton* Singleton::getInstance() {
if (singleton_ptr== nullptr ){
pthread_mutex_init(&mutex, nullptr );
pthread_mutex_lock(&mutex);
if (singleton_ptr== nullptr ){
singleton_ptr=new Singleton();
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
}
return singleton_ptr;
}
Singleton::Singleton() {
std ::cout <<"constructor" <<std ::endl;
}
Singleton::~Singleton() {
std ::cout <<"destructor" <<std ::endl;
singleton_ptr= nullptr ;
}
void Singleton::destroy() {
if (singleton_ptr){
pthread_mutex_init(&mutex, nullptr );
pthread_mutex_lock(&mutex);
if (singleton_ptr){
delete singleton_ptr;
singleton_ptr= nullptr ;
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
}
}
int main() {
Singleton *a=Singleton:: getInstance();
Singleton *b=Singleton:: getInstance();
if (a==b) {
std: :cout<<"a==b" <<std : :endl ;
}
Singleton *c=Singleton:: getInstance();
std: :cout<<a<<std : :endl ;
std: :cout<<b<<std : :endl ;
std: :cout<<c<<std : :endl ;
a->destroy();
// b->destroy();
a= nullptr;
std: :cout<<a<<std : :endl ;
std: :cout<<b<<std : :endl ;
std: :cout<<c<<std : :endl ;
return 0 ;
}