fbpx

C++ interview questions on patterns like thread safe singleton and bridge

(Last Updated On: May 12, 2010)

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::instance() & get a pointer to a singleton of type Foo. Assume the existence of a class Lock which has acquire() & release() methods. The implementation should be thread safe & exception safe

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::instance = 0
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"< NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top