Re: @synchronized question
Re: @synchronized question
- Subject: Re: @synchronized question
- From: Shawn Erickson <email@hidden>
- Date: Mon, 24 May 2004 10:45:36 -0700
On May 24, 2004, at 9:15 AM, Mel Walker wrote:
I'm a little unclear about how @synchronized works. Can someone tell
me if I have this right?
For example, I have code that looks like this (logLock is an NSLock,
myTextView is a NSTextView):
-(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
_______________________________________________
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.