Make changes in the singleton class for multithreading
Q4) Implement a Singleton pattern as a template such that, for any given class Foo, I can call Singleton
class foo
{
public:
static foo* instance();
private:
foo() {}
~foo() {}
static foo* smInstance;
static Lock smMutex;
};
foo* foo::smInstance = NULL;
Lock foo::smMutex;
foo* foo::instance()
{
LockLocker lock(&smMutex);
if (smInstance == NULL)
smInstance = new foo();
return smInstance;
}
i think they expect a double checking lock
template
class Singleton
{
public:
T* Instance()
{
if(!instance)
{
Lock mutex; // RAII object which aquires mutex lock
if(!instance) // Double check
{
instance = new T;
}
}
return instance;
}
private:
Singleton(){}
~Singleton(){}
static T *instance;
};
In .cpp
static Singleton
Venkat on September 27, 2009 |Edit | Edit
sorry… the Instance() function should be static
Reply to Comment
ac on November 14, 2009 |Edit | Edit
and you should also make the operator= private for this class.
exception safe and thread-safe
template
class Singleton
{
public:
T* Instance()
{
if(!instance)
{
Lock lock(m_dataMutex); // RAII object which aquires mutex lock
if(!instance) // Double check
{
try
{
instance = new T;
}
catch(…)
{
cout<<"Exception encountered in Singleton::MyInstance"<