• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Techniques for thread communication
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.

References: 
 >Re: Techniques for thread communication (From: Eric Scharff <email@hidden>)

  • Prev by Date: benefits of introspection and loose typing
  • Next by Date: DragDropImageView
  • Previous by thread: Re: Techniques for thread communication
  • Next by thread: Re: Techniques for thread communication
  • Index(es):
    • Date
    • Thread