[c++-pthreads] Initialization of local static mutex

Mark Mitchell mark at codesourcery.com
Tue Oct 10 16:49:44 UTC 2006


Jean-Marc Bourguet wrote:
> Mark Mitchell wrote:
>> Roland Schwarz wrote:
> 
>>> 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?
> 
> I fail to see how the programmer can make the initialization thread-safe 
> if the compiler doesn't take care of it?  Lack of memory barriers could 
> make the bool indicating that the initialization is done visible, but 
> not the written value.

The programmer can't take care of it easily.

If the compiler doesn't do it for you, have to do things like:

   static int i;
   static bool initialized;

   lock_mutex();
   if (!initialized) {
     i = g();
     initialized = true;
   }
   unlock_mutex();

i.e., you have to manage the initialization manually.  And, yes, there 
are lots of problems with that, including exceptions being thrown by 
g().  So, it's a good feature for compilers to have.  Of course, since 
it makes initialization slower (and code bigger) in the single-threaded 
case, some programmers want to be able to turn off the compiler support.

-- 
Mark Mitchell
CodeSourcery
mark at codesourcery.com
(650) 331-3385 x713



More information about the c++-pthreads mailing list