Subj : Re: double-checked locking in C To : comp.programming.threads From : Laurent Deniau Date : Thu Jul 07 2005 11:25 am David Hopwood wrote: > 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. I was abusively talking of a jump while in fact the goal was to have a call. I don't know if processor can do tentative evaluation of a call, but the value it has to assigned is returned by value from the call. ld. .