Re: Techniques for thread communication
Re: Techniques for thread communication
- Subject: Re: Techniques for thread communication
- From: email@hidden (Peter Robinson)
- Date: Mon, 8 Sep 2003 23:21:17 +0100
Eric Scharff <email@hidden> wrote:
>
WorkerThread never accesses result, it works on workingCopy.
That makes things very simple.
>
So somewhere in my code I do
>
>
while (working) {
>
workingCopy = [[Result alloc] init];
>
// Does the work
>
[self setResult: workingCopy];
>
[workingCopy release];
>
}
>
>
-(void)setResult: (Result *)newResult {
>
[myLock lock];
>
[result release];
>
result = [newResult retain];
>
[myLock unlock];
>
}
Fine.
>
Is this the right way to write the getter?
>
>
-(Result *)result {
>
Result *r;
>
>
[myLock lock];
>
r = result;
>
[myLock unlock];
>
return r;
>
}
>
>
Is this over-paranoid?
Not quite paranoid enough I'm afraid. Suppose -[setResult:] and
-[result] are called simultaneously, and -[result] gets the lock first.
The instance variable is assigned to r, but as soon as -[result]
releases its lock, -[setResult:] sends the object still pointed to by r
a release message, possibly before the -[result] method has even
returned.
This is what you need in this case:
-(Result *)result {
Result *r;
[myLock lock];
r = [[result retain] autorelease];
[myLock unlock];
return r;
}
The -[autorelease] puts r in the caller's autorelease pool (as opposed
to the worker thread's), so it will not be released until after the
caller returns.
>
can one assume the assignment is atomic?
I always have made that assumption, and therefore assumed that the
following is totally thread safe:
-(void) setIntResult: (int) val { intResult = val; }
-(int) intResult { return intResult; }
I'd like to know if that's wrong.
Peter
_______________________________________________
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.