Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Gianni Mariani Date : Mon Jan 17 2005 05:40 pm roland wrote: > I stumbled about the following problem: > > struct A { > A() { > } > ~A() { > } > }; > > void foo() > { > static A aA; > } > > The ctor of aA might be called "the first time control passes through > its declaration". (C++ Standard 6.7) GCC 4.0 will have it's bug fixed in this area. Other compilers seem to have bugs. > > This is fine in a single threaded application. But hows about > multithreaded? The standard is clear "the first time control passes through its declaration". Threads are irrelevant - it must be constructed once. Compilers that provide MT support must therefore abide by it, regardless. All C++ compilers I have used have some level of thread support and hence are required to support thread safe static constructors as per the standard. > > There obviously does exist a race condition for the flag that possibly > prevents second invocation of the ctor. Since this is compiler > depandant, is there a way to safely use local static objects, or > should they simply banned from MT applications? Get the compiler fixed. > > Any ideas? In theory, you can place a mutex around the code yourself. Not tested, but I would probably do somthing like this: #define MTSafeStatic( Type, Name, Initializer ) \ static Type * x_ ## Name; \ \ if ( ! x_ ## Name ) \ { \ Lock l_lock( StaticInitializerMutex );\ \ if ( ! x_ ## Name ) \ { \ static Type v_ ## Name Initializer; \ \ x_ ## Name = & v_ ## Name Initializer; \ } \ } \ \ Type & Name = * x_ ## Name; \ // End macro // Note that there must be exactly one StaticInitializerMutex // otherwise you will be making deadlock posssible when // you have recursive constructors void Foo() { static FooBar x = "ABC"; } becomes void Foo() { MT_SafeStatic( FooBar, x, = "ABC"; ) } .