Re: Confused about a thread-safe singleton example.
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-6280-1228270654-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
jason.cipriani@gmail.com writes:
static Mutex mutex;
static TheClass *instance;
static TheClass * getInstance () {
MutexLocker lock(mutex);
if (!instance)
instance = new TheClass();
return instance;
}
The example then goes on to talk about how double-check locking is
broken, etc. My question is pretty much this: Is C++ static
initialization thread-safe? If not, then how does the above example
safely use "mutex"? If so, then what is wrong with this:
static TheClass instance; // not a pointer
static TheClass * getInstance () {
return &instance; // it's correctly initialized?
}
The reason I ask is I almost never see it done like that, I always see
blog entries and articles that say the same thing "store instance in a
pointer, use a mutex to protect, and p.s. double-checked locking is
broken". It seems like doing it lock-free is made out to be a hard
problem, so *if* having a static instance works (but I don't know if
it does, that's my question), then why doesn't anybody ever suggest
it?
Setting aside the fact that there's no such thing as threads or mutexes in
the C++ language (at least not yet), so you are using a platform specific
library here.
Your statically declared instance gets constructed at some unspecified point
before your main() function gets invoked. If you have other objects in
static scope, it is unspecified the order in which all your static instances
get initialized. This may be undesirable. It's possible that it is necessary
to construct your singleton in a more controlled fashion, after all your
other objects, in static scope or otherwise, get initialized. Using a
dynamically-allocated pointer to your singleton, and protecting it with a
mutex, gives you the means to accomplish that.
--=_mimegpg-commodore.email-scan.com-6280-1228270654-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEABECAAYFAkk17D4ACgkQx9p3GYHlUOJotgCbBco+Xrs5u0U86IOADd+oeuyp
o+sAnR7hGaj1VR/CVxUYE6r4Y9lC6EPK
=yrMy
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-6280-1228270654-0001--