Re: retain/release question about Apple docs
Re: retain/release question about Apple docs
- Subject: Re: retain/release question about Apple docs
- From: Shaun Wexler <email@hidden>
- Date: Mon, 6 Mar 2006 16:53:52 -0800
On Mar 6, 2006, at 4:27 PM, Martin wrote:
I'd add that you should make sure that (b) is only evaluated once:
#define REPLACE( var, expr ) { \
id _varValue_ = [(expr) retain]; \
[var release]; \
var = _varValue_; \
}
Yes, you are quite correct; but it's even simpler that that:
#define REPLACE(a, b) \
do { register __typeof(a) _a_ = (a); _a_ = [(b) retain]; \
#if __ppc__ \
__asm__ volatile ("sync") \
#endif \
[_a_ release]; } while (0)
Since once you get comfy with macros like this you might do stuff
like:
REPLACE( _ivar, [string lowercaseString] );
#if __ppc__ \
__asm__ volatile ("sync") \
#endif \
Shaun, what's that assembly for?
The sync instruction causes all CPUs to wait until pending stores
have completed, amongst other niceties. This ensures that all CPUs
see the new pointer (id) before the underlying storage for the old
"a" object is [potentially] freed, avoiding a non-mutexed getter race
situation and possible disastrous result.
A thread-safe (32-bit addressing) universal solution would be:
#define SAFE_REPLACE_OBJECT(a, b) \
do { register volatile __typeof(a) _a_; register __typeof(b) _b_ =
[(b) retain]; \
while (!OSCompareAndSwap((UInt32)(_a_ = (a)), (UInt32)_b_, (UInt32 *)&
(a))); \
[_a_ release]; } while (0)
~YMMV~ ;)
--
Shaun Wexler
MacFOH
http://www.macfoh.com
"I never let schooling interfere with my education." - Mark Twain
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden