Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Gianni Mariani Date : Thu Feb 10 2005 11:12 pm Giancarlo Niccolai wrote: > > // Change this with your favorite static initializer method. > Item &cofu() { > static Item *the_item = 0; > if ( the_item == 0 ) { > the_item = new Item(); // compiler lock here. > } > return the_item; > } My understanding is that with GCC 4.0's fix for static local initializers, the "fix" is not invoked in your code above. The line: static Item *the_item = 0; is an initialization of a POD with a contant, this is done at compile time, not run time. IRC, the C++ standard mandates that this is so. The line: the_item = new Item(); // compiler lock here. Has no compiler lock whatsoever. However, if you had written the code like: Item &cofu() { static Item the_item; return the_item; } The compiler would provide a lock on the initialization of the_item. If the compiler did not, you could do this to mimic what the GCC 4.0 compiler does (not sure about the __thread thing): #define MTSafeStatic( Type, Name, Initializer ) \ static __thread Type * x_ ## Name; \ \ if ( ! x_ ## Name ) \ { \ Lock l_lock( StaticInitializerMutex );\ \ static Type v_ ## Name Initializer; \ \ x_ ## Name = & v_ ## Name Initializer; \ } \ \ Type & Name = * x_ ## Name; \ // End macro Item &cofu() { MTSafeStatic( Item, the_item, ); return the_item; } ** __thread is a fast thread specific local variable initialized to null for every thread. If your compiler supports __thread extensions then this is about as fast as you could possibly do without any locking, no barriers are needed since the StaticInitializerMutex will provide that. Also, the StaticInitializerMutex is a recursive mutex for the whole application. .