Subj : Re: double-checked locking in C To : comp.programming.threads From : David Hopwood Date : Thu Jul 07 2005 02:59 am Laurent Deniau wrote: > David Hopwood wrote: > >> 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. You're mistaken; processors can reorder memory accesses across jumps. -- David Hopwood .