App hangs at __psynch_mutexwait App hangs at __psynch_mutexwait multithreading multithreading

App hangs at __psynch_mutexwait


By having several people look at the code, and trace through the long complicated code paths, we found what appears to have been the culprit.One method running in a background thread was finding and using some Core Data objects and using the main-threads context.

Sure would have helped a LOT if IOS would give useful stack traces.


This has seen when a related entity in another context (and on another thread) has been modified but not yet persisted.

The scenario:

A --> B

Due to a bug B had pending changes, in another context, on another thread. The Bug caused B to hang around instead of saving or rolling it back.Attempting to save A in the current context/thread will will cause the wait for the other thread to release the lock on B.

Only successful way to trouble shoot was to list all pending entities and compare to ones in the blocked thread. Took a while :(

I am still looking for something that list all locks on the database and entities.


This usually happens when one tries to access Core Data objects on a background thread using the main-threads context OR using the same managed object context on different threads (background or main) at the same time. For more details check out Core Data concurrency rules.

So to avoid both cases, the main rule is, each thread must have its own managed object context and initialize that context exactly where it's going to be used.

For example:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{   //   // Prepare your background core data context   //    if (self.privateContext == nil)   {       self.privateContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];       [self.privateContext setParentContext: - main managed object context - ];       [self.privateContext setUndoManager:nil]; // this context should not manage undo actions.   }   //   //   Do any Core Data requests using this thread-save context   //   .   .   .});