Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Giancarlo Niccolai Date : Thu Feb 03 2005 10:21 pm Gianni Mariani wrote: > David Schwartz wrote: >> "Gianni Mariani" wrote in message >> news:haGdnR1nYeaWBJzfRVn-tg@speakeasy.net... >> >> >>>Simply because the C++ standard is quite specific in that static function >>>local variables (non POD) must be initialized exactly once on the *first >>>time* that control passes through the variable. All we're doing here is >>>enforcing this requirement. >> >> >> No! The C++ standard says nothing about threads. The C++ standard >> does >> not provide *any* guarantees in the context of threads.' > > Exactly. Hence, any platform that supports threads must do so in a way > that it maintains the requirements of the C++ standard, otherwise it is > BROKEN. > > A threading standard >> must specifically restate any C++ standard guarantees that it provides in >> the context of threads. If we're talking POSIX, POSIX specifically >> requires accesses to shared data (which the static object is) to be >> protected by mutexes. > > Only if the shared data is modified. No, also if it's just read; anyhow, POSIX does not require that the compiler prevents any thing that may ever become shared data to be unconditionally protected: it requires that the programmer protect its shared data when it can be proven that it is or may be shared at that point in the code. C++ says nothing, true, but there's no need for that. It's exactly the same: there is NO reason, NO REASON AT ALL, to forcefully protect all the data that may possibly be ever shared (especially if the nature of this protection is doubtful). Only the data that IS REALLY shared, or that may get concretely shared, and only in the points in which it is shared, must be protected, and nothing more. Doing it more is not just an overkill: is an error that can lead to cross-locking or other potential problems. One of the most important things that you have to understand is that "shared data" may be more than a single class, and that a single class may present several sets of shared data each one to be protected in a different context and in a different way. Do you really think that a compiler can ever get smart enough to cope with this complexity without breaking things? There's an old motto in IT that says "if it isn't broken, don't fix it". C++/threads have nothing broken; you can do perfectly treadsafe programs with them. You must just know what you are doing, as always, and as always square or cubic when you handle threads. Bests, Giancarlo Niccolai. .