marcoarment/FCModel — pull request #6 by dhennessy (2013-09-21 09:37:29+00:00)
Title: Fix deadlock in -instanceWithPrimaryKey

I was running into a regular lockup in my code when the following situation occurred:

THREAD A THREAD B
// My code // My code
+[FCModel instanceWithPrimaryKey:...] ACQUIRE g_instances lock
-[FCModel allInstances]
-[FCModel _instancesWhere:...]
-[FMDatabaseQueue inDatabase] ACQUIRE databaseQueue lock
-[FCModel _instancesWhere...]
+[FCModel instanceWithPrimaryKey:...] WAIT g_instances lock
+[FCModel instanceFromDatabase...]
-[FMDatabaseQueue inDatabase] WAIT databaseQueue lock

At this point, thread A has acquired g_instances and is waiting for databaseQueue, and thread B has acquired databaseQueue and is waiting for g_instances. Neither thread can proceed and everything stops.

The solution is to ensure that g_instancesReadlock is unlocked before any potential database calls are made.