Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : gniccolai Date : Thu Feb 17 2005 03:26 am gottlobfrege@gmail.com wrote in message news:<1108619955.159201.299810@z14g2000cwz.googlegroups.com>... > Alexander Terekhov wrote: > > gottlobfrege@gmail.com wrote: > > [...] > > > operations, which, I hope is slightly better than boost's version, > > > which uses a global named mutex...) > > > > What's your problem with global named mutexes created lazily > > on once()'s slow path? Note that are destructed pretty soon. > > > > regards, > > alexander. > > Also, my original reason for looking at once wasn't for performance (I > didn't even know about boost once or pthread_once), it was syntax. I > wanted (and made) this syntax: > > int foo() > { > static Once once; > > if (Once::Sentry sentry(once)) > { > // do some stuff once > } > > // no thread gets here until the once stuff is done. > // (and only done once, of course.) That's not following the pthread_once semantic: all the threads get there even if once stuff is still NOT done. However, this semantic (do once AND lock the section, or lock the section and DO only once), may break a correctly built static initialization (i.e. a constructor called to initialize the static object) for the reason I already told. > By the way, what do people think should happen in the case of recursion > - ie calling foo() inside the Once block? (Or similar recursion with > pthread_once?) I could throw an assert, or just not worry about it (I > suspect my current implementation lets them back into the once block > and recurses. Alternatively I could deadlock, but that seems even > worse...) Recursions in pthread_once does nothing strange (the second time a thread meets pthread_once, it just skips it). Recursion with your semantic will deadlock, unless the mutex you use is recursive. In that second case, all will work fine (the block is executed only once). Gian. .