Re: Thread safety question
Re: Thread safety question
- Subject: Re: Thread safety question
- From: Rich Seibel <email@hidden>
- Date: Fri, 18 Feb 2005 08:59:00 -0600
On Feb 18, 2005, at 4:47 AM, Steve Gehrman wrote:
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?
This is a slight variation of the double check pattern that the ACE
(Open Source MiddleWare in C++) uses, shown below.
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;
}
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.
Thanks,
Rich
Thanks.
-steve
_______________________________________________
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
_______________________________________________
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