• 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
Re: Memory Management
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Memory Management


  • Subject: Re: Memory Management
  • From: Chris Purcell <email@hidden>
  • Date: Wed, 30 Jul 2003 14:12:15 +0100

- (void)setName:(NSString *)newNamemet {
[newName retain];
[_name release];
_name = newName;
}

This is fine.

Thread safe ?

No, obviously not. It would need a lock around it, if you were to do
it that way. The question then becomes: what's faster, a lock or an
autorelease? In most situations an autorelease, I would think, since
it would be a once-off, versus potentially having to acquire the lock
many times. Unless of course your value changes far more frequently
than you access it, in which case I suppose a lock might be faster.

You would always need a lock around it. Autorelease is not magic. It certainly won't get you thread safety.

Yes it will, in this case. The problem with the previous example (above) is that you release [and possibly dealloc] your existing instance, then could have some other code which refers to _name before you change it to newName. _name at this point is a dangling pointer. If instead you autoreleased your existing instance, any chance reference to _name before you change it would still return a valid, existing object.

Not really, since the autorelease will occur on the thread doing the setName: call, so any other threads will not benefit. Imagine if another thread was running a non-mutexed read at the same time:

Thread 1: (in accessor) reads _name
**Thread 1 suspended**
Thread 2: (in setter) retains newName, autoreleases old value, then purges autorelease pool
**Thread 1 reactivated**
Thread 1: uses value of _name and segfaults

If you want thread safety, you *need* a lock, and you need to retain/copy/autorelease the object in the thread using it *before* that lock is released, if it will be used outside the mutex protection. No other solution is possible within Cocoa's retain-release system.

Kritter out
_______________________________________________
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.

  • Prev by Date: Floating palette close behavior
  • Next by Date: Stef, Dienstag, Prachi many thanks!!--for scanf answer (nm)
  • Previous by thread: Re: Memory Management
  • Next by thread: Re: Memory Management
  • Index(es):
    • Date
    • Thread