Subj : Re: double-checked locking in C To : comp.programming.threads From : David Hopwood Date : Wed Jul 06 2005 01:40 am 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. -- David Hopwood .