• 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
NSLock optimizations
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

NSLock optimizations


  • Subject: NSLock optimizations
  • From: Steve Gehrman <email@hidden>
  • Date: Sun, 25 Aug 2002 01:01:58 -0700

I have an object that lazily sets it's variables. For example:

- (BOOL)isPhucked;
{
if (isPhucked == -1)
{
isPhucked = (blah == foo) ? 0:1;
}

return (isPhucked == 1);
}

I want this to be thread safe, and I don't want to call lock, unlock once the variable has been set, so I tried something like:

- (BOOL)isPhucked;
{
if (isPhucked == -1)
{
[myLock lock];

// must check again since lock could have been released by another thread that initialized isPhucked
if (isPhucked == -1)
{
isPhucked = 0;

if (blah)
isPhucked = 1;
}

[myLock unlock];
}

return (isPhucked == 1);
}

I have discovered that this is not thread safe since the first line check of isPhucked is not protected by the lock. The call from a second thread could check isPhucked == -1 after the first thread sets it to 0, before the if (blah) isPhucked = 1; is executed.

My question is: Is there a way to structure this code so it is fully thread safe. The thing I'm trying to avoid is constantly calling lock and unlock every time this function is called once the variable has been successfully initialized. Is calling lock and unlock slow? Maybe the answer is to just call lock and unlock everytime?

Thanks,

--
Steve Gehrman
email@hidden
http://www.cocoatech.com
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Follow-Ups:
    • Re: NSLock optimizations
      • From: Nathan Day <email@hidden>
    • Re: NSLock optimizations
      • From: Ondra Cada <email@hidden>
  • Prev by Date: Re: NULL SEL arguments in Jaguar?
  • Next by Date: Re: NSLock optimizations
  • Previous by thread: Re: NSDocument: Saving more than 1 file???
  • Next by thread: Re: NSLock optimizations
  • Index(es):
    • Date
    • Thread