title: Core data, threads saving to a persistant store w/out locking, whats could go wrong?
body: <p>My application downloads and caches photos into coreData in background threads while still allowing the user to poke around in the application.  Currently after a photo's data is done downloading I start a thread to save it to coredata using the suggested shared storeCoordinator and thread-owned context then merge on the main thread, I also lock the shared coordinator until just before merging.  This locking causes performance issues though on reads by the user.</p>
  
  <p>Do I need to lock here?  What are the pitfalls of not locking?  The flow is essentially:</p>
  
  <pre><code>-(void)saveThreaded:(args)args {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  [NSThread setThreadPriority:.5];
  
  [_appDelegate.persistentStoreCoordinator lock];  //necessary?
  NSManagedObjectContext *_moc = [[NSManagedObjectContext alloc] init];
  [_moc setPersistentStoreCoordinator: [_appDelegate persistentStoreCoordinator]];
  
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadControllerContextDidSave:)
                                               name:NSManagedObjectContextDidSaveNotification object:_moc];
  ...&lt;blah blah&gt;...
  }
  
  - (void)threadControllerContextDidSave:(NSNotification*)saveNotification {
  // need to unlock before we let main thread merge  
  [_appDelegate.persistentStoreCoordinator unlock];
  [self performSelectorOnMainThread:@selector(mergeToMainContext:) withObject:saveNotification waitUntilDone:YES];
  }
  
  - (void)mergeToMainContext:(NSNotification*)saveNotification {
  NSError *error;
  [_appDelegate.managedObjectContext mergeChangesFromContextDidSaveNotification:saveNotification];  
  if (![_appDelegate.managedObjectContext save:&amp;error]) {
  &lt;handle error&gt;
  }
  }
  </code></pre>