dimanche 1 février 2015

thread safe singleton pattern design for review in c++

Below are two design of thread safe singleton design pattern . I would appreciate if anybody share their thought on both designs and point out if there is any issue. Design 1 follow the DCL (double check locking) and Design 2 based on assumption that local static variable can be initialized only once, which seems to be true for only for c++0x compiler. so in this case if same code is targeted to other compiler like c99 then what needs to change in current design. Please enlighten on this.


Design 1



#include <iostream>

#include<pthread.h>

using namespace std;

class Singleton
{

public:

static Singleton* getInstance();
void fun()
{
cout<<"singleton";
}
private:

Singleton() {std::cout << "Ctor\n";};

~Singleton() {std::cout << "Dtor\n";};

Singleton(const Singleton&);

const Singleton* operator=(const Singleton&);

static Singleton* instance;

static pthread_mutex_t myMutex;
};
Singleton* Singleton::getInstance()
{
if(instance==0)
{
pthread_mutex_lock(&myMutex);

if(instance==0)
{

cout<<"only need to come here once";

instance=new Singleton();
}

pthread_mutex_unlock(&myMutex);

}
return instance;
}

Singleton* Singleton::instance=0;

pthread_mutex_t Singleton::myMutex=PTHREAD_MUTEX_INITIALIZER;;

int main()
{

Singleton *s1 = Singleton::getInstance();
s1->fun();
return 0;

}


Design 2:



#include <iostream>

#include<pthread.h>

using namespace std;

class Singleton
{

public:

static Singleton& getInstance();
void fun()
{
cout<<"SIngleton";

}


private:

Singleton() {std::cout << "Ctor\n";};
~Singleton() {std::cout << "Dtor\n";};

Singleton(const Singleton&);
const Singleton* operator=(const Singleton&);
static pthread_mutex_t myMutex;

};



Singleton &Singleton::getInstance()
{
pthread_mutex_lock(&myMutex);
static Singleton instance;
pthread_mutex_unlock(&myMutex);
return instance;
}


pthread_mutex_t Singleton::myMutex=PTHREAD_MUTEX_INITIALIZER;;

int main()
{
Singleton &s1 = Singleton::getInstance();
s1.fun();
return 0;

}

Aucun commentaire:

Enregistrer un commentaire