views:

341

answers:

1

I have an application that pulls data from the web, parses them, and compiles the results in a search interface. Since the data are not co-dependant, it made sense to multi-thread the application to execute multiple fetches and parses simultaneously. I use NSInvocationOperation on a search and parse object I have written to execute this function.

In the controller object I have the following method:

-(void) searchAndParseAsynchronously { 
 NSPort *serverPort = [NSMachPort port];
 NSConnection *serverConnection = [NSConnection connectionWithReceivePort:serverPort sendPort:serverPort];
 [serverConnection setRootObject:self];
 for (NSURL *urlToProcess in self.urlsToFetch)
 {
  BaseSearchParser *searcherForURL = [BaseSearchParser newSearchParserWithParameters:self.searchParams];
  searcherForURL.urlToDocument = urlToDocument;

  SearchThreader *searchThreader = [SearchThreader new];
  searchThreader.threadConnection = comConnection;
  searchThreader.targetSchema = searcherForURL; 
  NSInvocationOperation *threaderOperation = [[NSInvocationOperation alloc] initWithTarget:searchThreader 
                                                                                        selector:@selector(executeSearchParse) 
                                                                                          object:nil];
  [self.operationQueue addOperation:threaderOperation];
 }
}

The application relies on Core Data, which I've gathered is mostly thread unsafe. I have a different NSManagedObjectContext for each search/parse operation (and one for the controller), and only pass the NSManagedObjectId between operations or proxy objects.

The operations communicate the completed parse results back to their controller via an NSConnection object. The controller constructs the NSConnection using an NSMachPort object, sets itself as the root object, and gives the same NSConnection object to each of the targets of the NSInvocationOperations. The controller then enqueues the NSInvocationOperation for execution in its own NSOperationQueue.

In the search threader object I have the following method:

-(void) executeSearchAndParse
{ 
 id parentServer = [threadConnection rootProxy];
 [parentServer setProtocolForProxy:@protocol(SearchParseProtocol)];

 NSArray *importResults = [targetSchema generatedDataSetIds];

 [parentServer schemaFinished:targetSchema];
 [parentServer addSearchResults:importResults];
}

I believe I have followed the Apple example of generic inter-thread communication given here.

I have to say that most of the time, this works beautifully: The notifications from the NSConnection rootProxy are posted to the run loop in the main thread as expected and wait for pickup until the controller object is ready. However, in some of my test cases it causes Core Data to grind to a screeching halt because sometimes the messages make it to the controller object in the same thread as the NSInvocationOperation object which is calling the rootProxy object.

I've placed a debugger point in the controller on the message which is sent when the search/parse operation is complete, and sure enough, sometimes (just sometimes) the executing thread is not the main one. Does anyone have an idea as to why this might occur? Or, is there a simpler way to construct inter-thread asynchronous communication? OR is my approach for Core Data totally off-kilter?

Thanks in advance!

+1  A: 

I don't see anything wrong with your approach and have used NSConnection in similar manner before. The only I thing I see is that I just used NSPort instead of using NSMachPort explicitly.

Or, is there a simpler way to construct inter-thread asynchronous communication?

I don't think Apple is promoting ditributed objects for inter-thread communication anymore. IIRC this guess is mostly based on documentation that I have seen mentioned which really promotes DOs for inter-thread communication but which since have been removed or edited.

I also think that the thread-related performSelector: methods on NSObject are much easier to use:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait

(while the second one is only available from 10.5 on).

Adrian
Thanks for your response. I have seen the `performSelectorOnMainThread` message implicated in the documentation earlier, but shied away from it due to its perceived low-level nature. I will give this a shot later today. Additionally, (should it work) it simplifies the design of the framework quite a bit. Those ports and connections can get messy quick!Thanks again!
zwerdlds