Re: @synchronized question
Re: @synchronized question
- Subject: Re: @synchronized question
- From: Mel Walker <email@hidden>
- Date: Mon, 24 May 2004 13:46:19 -0600
Thanks everyone for all your help. I think I've got it. :-)
Mel
On May 24, 2004, at 11:45 AM, Shawn Erickson wrote:
On May 24, 2004, at 9:15 AM, Mel Walker wrote:
-(void)doSomething {
[logLock lock];
...
[myTextView scrollRangeToVisible:scrollRange];
[myTextView setNeedsDisplay:YES];
[logLock unlock];
}
can I replace this with the following:
-(void)doSomething {
@synchronized(myTextView) {
[myTextView scrollRangeToVisible:scrollRange];
[myTextView setNeedsDisplay:YES];
}
}
or should I do something like this:
-(void)doSomething {
@synchronized(self) {
[myTextView scrollRangeToVisible:scrollRange];
[myTextView setNeedsDisplay:YES];
}
}
Basically synchronized (compiler generated code) uses the provided
object to find a mutex to use (something akin to a NSRecursiveLock).
Note synchronized doesn't behave the same as the use of NSLock in the
above sample since synchronized allows recursion in the same thread
while NSLock does not.
So if you use myTextView then anyone else synchronized against that
same object will be mutually exclusive for the wrapped block of code.
If you use "self" then anyone else synchronized against that same
object (whatever self references in this example) will be mutually
exclusive.
The nice thing about synchronized (in addition to its simple clear
syntax) is that if an exception is thrown while in the synchronized
block the mutex is automatically released as the block is exited. In
your example above using NSLock if an exception is thrown (without the
addition needed catch clauses) the logLock will not be unlocked and
hence a deadlock will likely happen the next time around.
Also note the @try/@catch/@finally clauses added.
-Shawn
--
Mel Walker <email@hidden>
_______________________________________________
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.