Re: Confused about a thread-safe singleton example.
On Dec 5, 10:32 am, "Chris M. Thomasson" <n...@spam.invalid> wrote:
"James Kanze" <james.ka...@gmail.com> wrote in message
[...]
I did (on a Sun Sparc, under Solaris). It's true that you
need the fences, and that they do increase execution time,
but they're unavoidable in any working solution anyway.
There not unavoidable for certain lock implementations
(asymmetric Dekker algorithm for one):
http://groups.google.com/group/comp.programming.threads/browse_frm/th...
See?
No. I don't see. Some sort of fences or membar instructions
are certainly necessary if you expect the other threads to see
your writes.
(The code you posted is NOT thread safe, and will not work
on any number of architectures, including Sparc, Alpha,
Itanium...)
The pseudo-code I posted is thread-safe. It uses POSIX Thread
`pthread_once()' for the initialization of the Meyers singleton.
`pthread_once()' synchronizes the memory.
Except that there were control flows which used the variables
without going through pthread_once:
static T* instance() {
if (! g_tls) {
pthread_once(&g_once, g_init);
g_tls = g_obj;
assert(g_tls);
}
return g_tls;
}
All you've done is replace the scoped mutex lock in double
checked locking with pthread_once; that doesn't solve anything.
If a thread sees g_tls non-null, there's no guarantee that it
will see a fully constructed object.
--
James Kanze (GABI Software) email:james.kanze@gmail.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