What is the problem with writing singleton in multithreaded enviroment

R

Ronen Yacov

Hi everybody,

When declaring a singleton, we write:

static CMySingle::instance()
{
static CMySingle instance;
return instance;
}

Why should there be a problem in a multithreaded enviroment?
If one thread creates a static object the other threads will have the
same
instance (becuase its static).

And if there is a problem, how the docuble check locking solves it?
 
M

Milind

What problem are you anticipating?? Is there something specific that
you are looking for. We use implementation which is pretty similar to
what you have quoted and it works fine with around 40 threads running
in the system.
Kindly, give more details.

~M
 
R

robbies

I did a little search of old group threads, and this popped up:
http://groups.google.com/group/comp...bbe602cde9d/fc1b524310a37e9e#fc1b524310a37e9e

The jist of it is, apparently, as the thread starter discovered, the
static construction of an object isn't an atomic operation. When it
gets compiled, it is turned into a set of instructions where a flag is
checked before the object is instantiated (which makes sense...I don't
know if the C++ Standard mentions whether it has to be done in the
certain way...I should look it up...). So if you think about it,
multiple threads could get past this check to instantiate the object,
which makes this not thread safe.
 
U

u.int.32.t

Milind said:
What problem are you anticipating?? Is there something specific that
you are looking for. We use implementation which is pretty similar to
what you have quoted and it works fine with around 40 threads running
in the system.
Kindly, give more details.

Your implementation will break on a SMP box. The correct (using
boost::call_once) is:

struct T
{
static T const & instance()
{
boost::call_once(&call_once,once_flag);
return get_instance();
}
private:
static boost::eek:nce_flag once_flag;
static T const & get_instance()
{
static T theT;
return theT;
}

static void call_once()
{
get_instance();
}

};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,192
Latest member
KalaReid2

Latest Threads

Top