Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : gniccolai Date : Wed Feb 16 2005 04:20 pm Marcin 'Qrczak' Kowalczyk wrote in message news:<87zmy4qzcy.fsf@qrnik.zagroda>... > gniccolai@yahoo.com (Giancarlo Niccolai) writes: > > >> It may not reenter the_safe_initializer. Reentering a static local > >> initializer before its previous run has finished is forbidden by the > >> C++ standard. > > > > There is no reason why I may not lock a mutex before entering a > > function (constructor or anything) that uses it as well (provided it > > is reentrant). > > You may lock the reentrant mutex again, but you may not enter the > static local initializer again. As the great A. Terekhof said: And? (now turn on the brain) > Since a deadlock caused by a mutex > around static initializer could happen only if you enter the local > initializer again, it never happens in code which isn't already > broken. False. The static initializer cannot be entered twice, but this is irrilevant: the example deadlocks exactly if the app mutex + static initializer mutex is entered the wrong way, even just once. In fact, I didn't say "run the app for hours", I said "run the app a billion of times", because the above deadlock can happen (only, obviously) the first time the object is initialized. > > > The above pattern usage is correct, under any standard, and an > > automated mutex locking done under the nose of the developer would > > break it. > > Please show me the real code, not pseudocode. The compiler doesn't > insert locking around calling functions; it inserts them around > dynamic initialization of static locals. I don't see a static local > in your code. No, I won't loose any more time: if you think the thing can go, write some code and run it several times. Provided that the order by which thread_1 and thread_2 run is random enough, it will often lock at startup (that is, the first time the object is initialized). It is absolutely basic MT programming, nothing more. And please, remember I am still talking about mutex guarded initialization; probably, a pthread_once thing would work in this context (depending on how it is implemented at low-level). Bests, Gian. .