Re: What is the problem with writing singleton in multithreaded enviroment
Ronen Yacov wrote:
Hi everybody,
When declaring a singleton, we write:
static CMySingle::instance()
{
static CMySingle instance;
return instance;
}
If I interpret your code correctly, this is not a proper singleton. But
I'm just guessing, seeing that the function has no return type.
Why should there be a problem in a multithreaded enviroment?
Because there's a potential race condition if/when two threads call
instance() at the same time and thus initialising instance twice.
If one thread creates a static object the other threads will have the
same
instance (becuase its static).
That's not the problem. The problem is that there is nothing in your
code that prevents instance from being initialised twice, at the same
time.
And if there is a problem, how the docuble check locking solves it?
Without resurrecting the discussion in another thread, *locking* per se
mostly solves the problem because it provides a mechanism to serialise
the check if the singleton has already been created.
Double checked locking doesn't really apply in your case anyway but
would normally look like this C++-like pseudo code:
foo* bar::get_foo_instance()
{
if (!foo_instance) {
lock.aquire();
if (!foo_instance) [
foo_instance = new foo;
}
lock.release();
}
}
The double check is necessary because in the above code, foo_instance
may have been initialised while the second was waiting for the lock,
This is a performance optimisation as aquiring the lock is usually a
fairly expensive operation and not necessary if foo_instance is already
initialised.
--
The lone C++ coder's blog: http://www.bsdninjas.co.uk/codeblog/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]