site_archiver@lists.apple.com Delivered-To: darwin-dev@lists.apple.com Apologies for using examples not immediately relevant to Darwin, but I don't want this idiom to become more prevalent. It is broken, even if in not so obvious ways. e.g void * myVariable = 0; volatile UInt32 sentinel = 0; void* instance(void) { if ( !OSCompareAndSwap( 0, -1, &sentinel)) { /* initialize variables */ if ( ! myVariable ) myVariable = allocateObject(); /* etc */ sentinel = 1; } else { while (sentinel != 1) /* yield, whatever that function is...pthread_yield()? */; } return myVariable; } _______________________________________________ Do not post admin requests to the list. They will be ignored. Darwin-dev mailing list (Darwin-dev@lists.apple.com) Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/darwin-dev/site_archiver%40lists.appl... On Feb 19, 2005, at 12:40 PM, Eric Gouriou wrote: Doesn't the use of a compare-and-swap or similar pattern (such as test-and-set) solve this problem without a lock at all? You could use myVariable as the sentinel also but that introduces other dependencies, and besides you probably don't want to declare it volatile. If you were to do that, to avoid the inline-ordering problem you'd assign the output of allocateObject to a local variable, then to the global. This email sent to site_archiver@lists.apple.com