Subj : Re: double-checked locking in C To : comp.programming.threads From : Laurent Deniau Date : Wed Jul 06 2005 11:44 am David Hopwood wrote: > amorox@gmail.com wrote: > >> Hi, >> >> I would like to use the DCL idiom (double-checked locking) to guarantee >> the once and only once execution of an initialization code: >> >> bool initialized = false; >> pthread_mutex_t mutex; >> >> void function(void) >> { >> if (!initialized) { >> pthread_mutex_lock(&mutex); >> if (!initialized) { >> initialized = true; >> init_code(); >> } >> pthread_mutex_unlock(&mutex); >> } >> } >> >> I know that in Java there were problems with this idiom due to the >> memory operation reorderings and these have been apparently solved in >> Java 1.4. > > > It has not been "solved"; it was not a goal of the new memory model to > solve it. Just don't use this idiom in Java. > >> Is there any problem using this idiom in a multithread C program? If >> affirmative would you explained why? > > > To a first approximation, anything that can go wrong with this idiom in > Java can also go wrong in C. While it is possible to solve the problems > by (nonportable, processor and compiler-specific) use of memory barriers, > it really isn't worth the hassle to do this in an application. > It might be worth it in a language implementation if you really know > what you're doing. There is a simple, portable, processor independent, compiler independent idiom which consists of delegating the work to an extern function, a function with an implementation in a different translation unit. void function(void) { if (!initialized) { pthread_mutex_lock(&mutex); if (!initialized) initialized = extern_init_code(); pthread_mutex_unlock(&mutex); } } The compiler is not allowed to assign initialized *before* extern_init_code() returns. The processor will not be able to do the same since this is a true jump with a return value. The assignment could be delayed but not after the unlock, so it is not a problem. a+, ld. .