• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Thread safety question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Thread safety question


  • Subject: Thread safety question
  • From: Steve Gehrman <email@hidden>
  • Date: Fri, 18 Feb 2005 02:47:02 -0800


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:

This email sent to email@hidden

  • Follow-Ups:
    • Re: Thread safety question
      • From: Ernesto Corvi <email@hidden>
    • Re: Thread safety question
      • From: Rich Seibel <email@hidden>
  • Prev by Date: TerminatorX Mac OS X Port
  • Next by Date: Re: Thread safety question
  • Previous by thread: TerminatorX Mac OS X Port
  • Next by thread: Re: Thread safety question
  • Index(es):
    • Date
    • Thread