ank wrote:
Hi,
I have some question about Singleton Pattern in C++.
I think I understand that static initialization order across
translation unit
is unspecified by the standard, but what can I do to ensure that some
kind of
static mutex is automatically initialized before the first use of it?
I cannot assume that this mutex is used only after executing main()
function because I need to use this mutex to lock singleton inside
initialization code and may apply double-check pattern.
Currently, I have very little experience with multithread programming.
I am not a native English speaker so my message may not be well
written.
Thanks in advance for any suggestions.
Well for starts, read this
http://www.cs.umd.edu/~pugh/java/mem...edLocking.html
This may kick off one of those interminable discussions where about half
of the participants will never get it.
To summarize, DCL isn't actually broken, it just that there aren't any
portable mechanisms to implement it correctly on all platforms. The
naive implementation using pointers assumes dependent load ordering. You
have to know which platforms this works on. It doesn't work on Alpha
processors.
There are design patterns let you implement DCL correctly. One is to have
each thread use a thread local variable whether it has a properly synchronized
view of the singleton data. The other is to only access the singleton via
a object of that class which has been properly synchronized with the singleton
in its construction. Access to the objects is assumed to be properly synchronized
also.
Initialization of a Posix pthread mutex is
pthread_mutex_t mutex = PTHREAD_MUTEX_I NITIALIZER;
For windows you can use a named Mutex which can be dynamically initialized in
a thread-safe manner. Windows CriticalSection initialization isn't thread-safe.
You can use compare and swap to initialize a CriticalSection . Example of this
here in the initFreeQueue subroutine. It also uses the access via object technique.
http://groups.google.com/groups?q=g:...6%40xemaps.com
I'd stay away of any naive spinlock implementations . Not only are they inefficient but
they're likely to be incorrect with regard to proper memory visibility, i.e. missing
necessary memory barriers.
--
Joe Seigh
When you get lemons, you make lemonade.
When you get hardware, you make software.