Re: A real threaded singleton
On Apr 9, 7:23 pm, EvilOld...@googlemail.com wrote:
In the stuff I've read about multi threaded singleton it seems to
assume that creating the Lock is atomic, and various sources,
including Sutter go for RAII.
if ( ! inst )....}
But I don't see how to do this with a real O/S API.
The ones I've looked at have a two step process to making a lock, they
require a "Create" function and a "Start Locking" function.
Any real answer will depend on the OS. Normally, you should be
able to create and initialize a mutex as a static object. If
not, you need a global mutex, which is used to synchronize the
creation of all of the secondary mutexes, and some tricky way of
In my own code, I generally find it acceptable to require that
threads don't start until after entering main, which means in
practice that the initialization of objects with static
lifetime, at least those which aren't in a dynamically linked
object, has occured. Thus, if you use a singleton, all you have
to do to ensure that it doesn't need a lock is to ensure that at
least one call to the instance function occurs during static
initialization. Something like:
bool dummyForInitialization = Singleton::instance(), tru ;
does the trick, as does:
Singleton* Singleton::ourInstance = &Singleton::instance() ;
A Lock class is presumably implemented as something like:
PrimitiveLock = CreatePrimitiveLock():
handle = StartLocking (PrimitiveLock);}
No. An RAII "lock" class is always based on an external mutex
or some other external synchronization primitive. You still
have the problem of creating that external object, of course.
Now if I have two threads there is a chance (albeit a small one) that
I end up creating two PrimitiveLocks
Thus far, I've got around it by making the PrimitiveLock a global
static like the Instance member.
That's normally what you do.
That makes error handling awkward, though if this is failing at such
an early stage then the program's not likely to work anyway.
If creating the lock fails, you have a problem. As you say, it
occurs at such an early stage that the program isn't likely to
work anyway, so you just abort with an error message.
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34