Re: Thread safety with background fetching
Re: Thread safety with background fetching
- Subject: Re: Thread safety with background fetching
- From: Joseph Kelly <email@hidden>
- Date: Thu, 31 Jul 2008 16:14:05 -0700
The only time you're sharing data across threads is via -
performSelectorOnMainThread:... which itself is thread safe.
So the main thing you have to work through is the memory management of
the data which XMLFetcherParser is passing to the -receiveItem: method
on the main thread. The convention is that things are created and
immediately added to the autorelease pool.
For instance, If the worker thread's autorelease pool gets released
right after it passes you the object on the main thread, that object
will become released, and you're left with a dangling pointer.
You might need to adopt a very tight convention that you retain the
object before sending it to the main thread, and once in the main
thread, autorelease it there.
Joe K.
On Jul 31, 2008, at 9:59 AM, Ben wrote:
Hi List,
Having read the Apple documentation and beginner guides on
threading, I am still a little confused about protecting my
variables from access by multiple threads.
A sample of my code is as follows:
@interface Class1 : NSObject
{
XMLFetcherParser *fetcherParser;
}
- (void)doBackgroundFetch;
- (void)receiveItem:(Item *)newItem;
@end
@implementation Class1
- (void)doBackgroundFetch
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
fetcherParser = [[XMLFetcherParser alloc] init];
[fetcherParser doYourThing];
[fetcherParser release];
[pool release];
}
- (void)receiveItem:(Item *)newItem
{
// Add newItem to an array
}
@end
For usage, the summary is that I do:
[NSThread detachNewThreadSelector:@selector(doBackgroundFetch)
toTarget:self withObject:nil];
and then -[XMLFetcherParser doYourThing] repeatedly sends newly
created objects to receiveItem: using the
performSelectorOnMainThread method. Once the spawned thread has done
this, it never uses the sent object again.
My question is how should I protect this code from thread related
problems? Do I just place @synchronized(){} blocks around the code
in receiveItem: and it's counterpart in the spawned thread? Or is
that just plain wrong? Or (likely) am I barking up totally the wrong
tree?
Regards,
Ben
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden