Re: @synchronized in thread safe accessors
Re: @synchronized in thread safe accessors
- Subject: Re: @synchronized in thread safe accessors
- From: Kyle Sluder <email@hidden>
- Date: Fri, 6 Feb 2009 19:09:20 -0500
On Fri, Feb 6, 2009 at 6:47 PM, Nick Zitzmann <email@hidden> wrote:
> With NS(Recursive)Lock, this isn't difficult:
Then why bother with @synchronized? Don't fix what isn't broke.
> OK, now what is the best way to do this using @synchronized instead of an
> NSLock? The getter method is obvious, but the setter isn't. My first thought
> was something like this:
You take a lock (or a @synchronized block) out on an object, not an
ivar slot. Therefore, locking on the value of the ivar doesn't make
sense; your thread might get interrupted within the @synchronized
block *after* it's reassigned the value of the ivar. Then when the
new thread tries to enter the @synchronized block, it will be taking
out a lock on a *different object* (the one pointed to by the new ivar
value), and the world ends.
Since you're using a setter, you need to take out the lock on a
different object. You might be able to take it out on self (a la Java
synchronization), or you might have to create a separate dummy
NSObject on which to take out the lock. And we've now come
full-circle to the ivarLock you had in your original implementation.
--Kyle Sluder
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden