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"<

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

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!
This entry was posted in Quant Development and tagged on by .

About caustic

Hi i there My name is Bryan Downing. I am part of a company called QuantLabs.Net This is specifically a company with a high profile blog about technology, trading, financial, investment, quant, etc. It posts things on how to do job interviews with large companies like Morgan Stanley, Bloomberg, Citibank, and IBM. It also posts different unique tips and tricks on Java, C++, or C programming. It posts about different techniques in learning about Matlab and building models or strategies. There is a lot here if you are into venturing into the financial world like quant or technical analysis. It also discusses the future generation of trading and programming Specialties: C++, Java, C#, Matlab, quant, models, strategies, technical analysis, linux, windows P.S. I have been known to be the worst typist. Do not be offended by it as I like to bang stuff out and put priorty of what I do over typing. Maybe one day I can get a full time copy editor to help out. Do note I prefer videos as they are much easier to produce so check out my many video at youtube.com/quantlabs