site_archiver@lists.apple.com Delivered-To: darwin-dev@lists.apple.com On Feb 18, 2005, at 4:47 AM, Steve Gehrman wrote: BOOL variable_initialized=NO; void* myVariable; NSLock* myLock; // assume lock has been initialized in main - (void)isThisThreadSafe; { if ( !variable_initialized ) { [myLock lock]; if ( !variable_initialized ) myVariable = allocateStuff(); variable_initialized = YES; [myLock unlock]; } return myVariable; } void* myVariable = 0; NSLock* myLock; // assume lock has been initialized in main void* instance(void) { if ( ! myVariable ) { [myLock lock]; if ( ! myVariable ) myVariable = allocateObject(); [myLock unlock]; } return myVariable; } Thanks, Rich Thanks. -steve _______________________________________________ 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/seibel_r%40ociweb.com _______________________________________________ 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... I have an object that lazily initializes it's variables when accessed and I want it to be thread safe, but I would like to avoid locking and unlocking the lock everytime every method is called. Below is one solution, but I don't think it is thread safe. I'm assuming that if variable_initialized is YES, then dataPtr must be valid, but I'm afraid that the OS might not guarantee when and how data is flushed, so could it be possible for variable_initialized and myVariable to be invalid? Can anyone confirm this, or offer advice on an alternate solution? This is a slight variation of the double check pattern that the ACE (Open Source MiddleWare in C++) uses, shown below. This will always work on a uni-processor. The problem comes when there are multiple CPUs and cache between the shared memory. The combined compiler, OS, and hardware must be able in insure that a variable, specifically myVariable above, is treated atomically across the processors. That is, myVariable, if changed in one processor and stored to memory, must be seen as changed on any other processor even if still in cache on that processor. Secondly, the lock must work atomically across all processors. The second requirement is a must for any multi-processor OS, so we can assume that one is true. Given our experience with ACE across many processors, we have only seen one we had to add a machine instruction to correct the first requirement. However, I am not a darwin developer and I would like assurance from them that this is true, in both the examples shown. This email sent to seibel_r@ociweb.com This email sent to site_archiver@lists.apple.com
participants (1)
-
Rich Seibel