Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Thread safety question



Hi Steve.

The problem you might encounter here, if you have global register allocation turned on, is that the compiler might cache 'variable_initialized' in a register.
So let's contemplate this scenario:
Thread1 -> Caches variable_initialized into R2, gets swapped out between the 'if ( !variable_initialized )' and the '[myLock lock]'.
Thread2 -> Executes the entire function and initializes the variable.
Thread1 -> Resumes execution, but since it cached 'variable_initialized' into R2, it still thinks its unitialized, and initializes again.

A portable solution to this problem is to declare 'variable_initialized' as:

volatile BOOL variable_initialized=NO;

The 'volatile' keyword hints the compiler not to cache the variable and force direct access to the variable every time it's accessed.

Ernesto.

On Feb 18, 2005, at 5: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?

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:
http://lists.apple.com/mailman/options/darwin-dev/email@hidden

This email sent to email@hidden

References: 
 >Thread safety question (From: Steve Gehrman <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.