Re: Techniques for thread communication
Re: Techniques for thread communication
- Subject: Re: Techniques for thread communication
- From: Greg Titus <email@hidden>
- Date: Mon, 8 Sep 2003 14:57:14 -0700
On Monday, September 8, 2003, at 12:11 PM, Eric Scharff wrote:
if the worker thread does not touch the result
thereafter, then you should have no problems.
Well, that's the thing. The getter lock is trying to avoid
1. worker calls setter
2. worker notifies sender on other thread
3. worker continues, calls setter
4. setter calls release on result but hasn't done assignment
yet
5. CONTEXT SWITCH
6. other thread calls result method, gets a now invalid thing
In Java (yeah, I know...) the way that I'd do this is with
syncronization of the instance methods, or
public synchronized void setResult(Result r) { result = r; }
public synchronized Result getResult() { return r; }
So my approach may be over-paranoid, but I don't think it's
broken. :)
Actually, if your "setter" looks like this (as you seem to be
describing) ...
-(void)setResult:(Result *)r
{
[myLock lock];
[result release];
result = [r retain];
[myLock unlock];
}
... then you are not being paranoid enough. What if:
1. worker calls setter
2. worker notifies sender on other thread
3. CONTEXT SWITCH
4. other thread calls result method, gets original result, unlocks
5. CONTEXT SWITCH
6. worker calls setter again, thus releasing first result
7. CONTEXT SWITCH
8. other thread tries to retain the object returned to it, which is now
invalid
In your "getter" you need to make sure that the result object is going
to stay around even if it is released from the "setter" thread, which
means it needs to be retained inside the lock. Thus:
-(Result *)result {
Result *r;
[myLock lock];
r = [result retain];
[myLock unlock];
return [r autorelease];
}
Hope this helps,
- Greg
_______________________________________________
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.