Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Thread safety question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Thread safety question

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?

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;

Can anyone confirm this, or offer advice on an alternate solution?



Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

Visit the Apple Store online or at retail locations.

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.