Subj : Re: double-checked locking in C To : comp.programming.threads From : Laurent Deniau Date : Wed Jul 06 2005 03:24 pm David Schwartz wrote: > "Laurent Deniau" wrote in message > news:dag5mv$2lf$1@sunnews.cern.ch... > > >>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. > > > Err, what?! If it's not guaranteed to work by the relevent standard, > it's not portable. You mean that calling a function between the pair lock/unlock is not portable? Which standard? >>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. > > > Not allowed by what? > > >>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. > > > Why can't the assignment be delayed until after the unlock? In principle it could if unlock does not need to synchronize its CPU cache, but in that case it has no effect on the semantic of the code above. > And what > guarantees that a CPU that never acquired the mutex sees the initialization > itself? I do not understand your point. If it does not acquire the mutex, it means that it has seen a valid value for initialized. So I do not see a problem. Could you give a sequence underlining the problem ? ld. .