thread-safe local static variable initialization

Michael Ball michael.ball at eng.sun.com
Tue Jun 8 02:19:42 UTC 1999


> Mike Ball wrote:
> > >(I mentioned this during last week's meeting, and Mike Ball said
> > >something to the effect that this was already fully described by
> > >the language.  But given that the language says nothing about
> > >multithreading to begin with, I'm not sure what he meant.)
> >
> > As far as I can tell, the language says that the automatic blocking 
> > issue isn't a valid approach.  It says what has to happen, and
> > it isn't that.
> 
> The language says it's undefined if control re-enters the  
> declaration recursively. It does not say much about threads. I think  
> you can read the standard as saying it's unnecessary, but not  
> incorrect.

If you look at the entire statement you find that it reads

"Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its
initialization. If the initialization exits by throwing an exception, the 
initialization is not complete, so it will be tried again the next time control 
enters the declaration. If control re-enters the declaration (recursively)
while the object is being initialized, the behavior is undefined."

The word "recursively" is normative, so eliminates that sentence from consideration.

One can, of course, make any extension to the language, but in this case I
think the extension invalidates some otherwise valid code.

The sentence I'm referring to is that the object is considered initialized upon the
completion of its initialization.  This is explicit, and the reason for it is
covered in the following sentence, which discusses an initialization that
terminates with an exception.   A person catching such an exception has the
right to try again without danger that the static variable will be initialized
in the meantime.

I don't see anything at all to justify semantics that say "After initialization is
started, Any other threads of control are blocked until that thread completes 
the initialization, unless, of course, it executes by an exception, in which case 
the other thread can do the initialization before the exception handler gets a 
chance to try again, except...."  Take an attempt to define the semantics as
far as you like.

The problem is that there is no way for the compiler writer to know what the
programmer really wanted to do.  I can (and will at some other date, if necessary)
come up with scenarios justifying a variety of mutual exclusion policies, including
none.

The solution is to let the programmer write the mutual exclusion, the same as
we do for every other potential race condition.

-Mike Ball-

It's a real mess, and, I claim, an unwise one to put in as an extension





More information about the cxx-abi-dev mailing list