My understanding of the @synchronized(obj) { ... }
directive in Objective-C is that it's essentially the same as the lock(obj) { ... }
construct in C#, i.e...
- Both create a kind of local, anonymous mutex tied to the specified object
- Any thread entering the
@synchronized
/lock
block must acquire that mutex prior to executing any code in the block (and will wait to acquire the mutex before proceeding if it's already reserved).
In C#, using lock(this)
is strongly discouraged (see Why is lock(this) {...} bad?) for an example), basically because you then have no control over who locks your mutex or when (since someone else could be using your object as a mutex).
I assumed that concept this would also apply to @synchronized(self)
in Objective-C, but I was told by a senior developer on my team that @synchronized
functions differently than lock
, and the concerns in the above SO post don't apply.
I guess my question is - what am I misunderstanding about @synchronized
? Why is @synchronized(self)
safe when lock(this)
is not?
Thanks.