Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : gniccolai Date : Sat Feb 19 2005 04:43 am Marcin 'Qrczak' Kowalczyk wrote in message news:<873bvu9ara.fsf@qrnik.zagroda>... > gottlobfrege@gmail.com writes: > > > "On return from pthread_once(), it is guaranteed that init_routine() > > has completed." > > Ah, I missed this sentence. So it's OK. > > I wonder if Giancarlo will claim that pthread_once is useless for the > very purpose it has been designed for. The rationale in SUSv3 shows > a C example for which static locals would be used in C++, and shows > how pthread_once makes it working in a multithreaded environment. Never claimed that. In fact, the rationale for pthread_once is: RATIONALE Some C libraries are designed for dynamic initialization. That is, the global initialization for the library is performed when the first procedure in the library is called. In a single-threaded program, this is normally implemented using a static variable whose value is checked on entry to a routine, as follows: static int random_is_initialized = 0; extern int initialize_random(); int random_function() { if (random_is_initialized == 0) { initialize_random(); random_is_initialized = 1; } ... /* Operations performed after initialization. */ } To keep the same structure in a multi-threaded program, a new primitive is needed. Otherwise, library initialization has to be accomplished by an explicit call to a library-exported initialization function prior to any use of the library. For dynamic library initialization in a multi-threaded process, a simple initialization flag is not sufficient; the flag needs to be protected against modification by multiple threads simultaneously calling into the library. Protecting the flag requires the use of a mutex; however, mutexes have to be initialized before they are used. Ensuring that the mutex is only initialized once requires a recursive solution to this problem. I cannot read anything about C++ static initializers. In fact, this rationale explicitly talks about external libraries, that CANNOT POSSIBLY SHARE DATA WITH THE CALLING PROGRAM, as a C++ constructor has the full right to do. So, if pthread_once must block calling threads untill its init_function is done, then it may deadlock correct programs exacly as the mutex guarding does. The only difference is that its (pthread_once) locking system is atomically initialized, but it doesn't moves our problem by a single millimeter. Also, there is no problem in calling pthread_once to initialize something in your same program, right, untill it shares (rightfully) data with the rest of the program, data that is otherwise protected. Because, if it shares data with the rest of the program, and the data is already proteced... you need not to use pthread_once!!! I don't want pthread_once to lock my initializers outside my control as I don't want mutexes to do that. Bests, Gian. .