Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Olivier Huet Date : Tue Jan 18 2005 10:23 pm Hello, roland a écrit : > 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) > > This is fine in a single threaded application. But hows about > multithreaded? > > 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? > MS VC++ 6 has this race condition : I had a funny bug with that few month ago :-) I've just checked, and VS 2003 has too. But in the theorical point of view, I'm not sure if it's a compiler issue, a librarie issue, or something else. Here are some arguments for "not" locking : C++ itself doesn't include any multithreading features, so why should the compiler include a lock here ? And if it does, what kind of lock : process wide (for multiple threads that access the variable), system wide (for multiple process that access the variable), etc etc. ? Here are some arguments for locking : to take again MS VC++, there are two "standard C and C++ libraries", one for single threading, and one for multithreading. Memory allocation fonctions are differents, standard C++ containers does include locks for "global access", ... So why isn't it in local static variables too ? I don't have "the answer" : does someone else have other arguments in one or the other direction ? Olivier Huet .