[c++-pthreads] Initialization of local static mutex
Mark Mitchell
mark at codesourcery.com
Mon Oct 9 22:09:51 UTC 2006
Roland Schwarz wrote:
>> However, in practice, your code is safe.
>
> This is what I was suspecting. But you will admit, that this is a
> different thing than prove.
Yes. For the reasons I stated, I don't think this is a provable thing;
the ISO C++ standard doesn't contemplate threads, so it's hard to reason
about them. The multi-platform C++ ABI used by G++ (and many other
compliers) does contemplate threads, but doesn't specifically address
the particular case that you posted.
> But if the initialization would have been done as
>
> foo()
> {
> static int bar;
> }
>
> bar would happen to be zero initialized on any conforming compiler.
> (before any other initializations take place)
> So zero initialization is more conservative with respect to the
> standard. Isn't it?
Yes. It would certainly be nice if PTHREAD_MUTEX_INIT were uniformly
zero, but on some hardware that's not feasible.
>> There are other issues around thread-safe initialization of statics
>> with a constant initializers which are addressed by some C++ ABIs, but
>> you have the simpler case of a constant initializer.
>
> Now that you have brought up this issue I am curious which "other
> issues" you are refering to.
void f() {
static int i = g();
}
Here, you cannot do the initialization statically; it must be done the
first time that f() is called. So, the key question is whether the
initialization is thread-safe. Does the programmer have to change that
initialization to be thread-safe, using locks in f()? Or does the
compiler take care of it?
The multi-platform C++ ABI defines library functions that compilers may
use to ensure thread-safe initialization of local statics. However,
using these functions is optional. So, some compilers do it, some
don't, and some do it only in certain modes.
--
Mark Mitchell
CodeSourcery
mark at codesourcery.com
(650) 331-3385 x713
More information about the c++-pthreads
mailing list