Ok, so I have multiple threads pull data from the persistent store (SQLite database) into a single NSManagedObjectContext (MOC) instance. I have tested it pretty thoroughly and in the case where operations overlap (t开发者_运维问答hread 4 loads into the MOC while thread 5 does so too), everything runs smoothly.
I have read (most of) the Core Data Programming guide and am aware that Apple does not condone this behavior, but I am wondering what the particular reasons are. In the docs Apple briefly alludes to the fact that not only writes are dangerous, but reads are as well because faulting may occur. How (if all the objects I load from the separate threads are individual entities with no overlap with each other)? And doesn't that just mean that the app will take a performance hit? So if I determine that a performance hit is a better tradeoff than increased memory usage, I would be inclined to use the one MOC (non-recommended) method.
I am going to revert to the recommended method in any-case but am just curious about the specific details of what could happen if these rules aren't adhered to. Thanks in advance.
I don't really know, but since nobody answered yet.
Not thread-safe is not thread-safe. Imagine the Core Data programmers put some unexposed instance variable in NSManagedObjectContext numberOfObjectsLoaded
. In thread A, you access a relationship of a managed object, foo.bar
. In thread B, you make a change to some completely unrelated object baz.number = 14
. Both foo and baz are faults. They get loaded. Both threads try to execute the line of code
numberOfObjectsLoaded += 1
But thread A reads numberOfObjectsLoaded, gets 77, then context switch. Thread B reads 77 also, adds 1, assigns 78. Back to thread A. It adds 1 to 77, which is what it read, gets 78, and also assigns 78 to numberOfObjectsLoaded. numberOfObjectsLoaded should have 79, but has 78. That inconsistency will lead to unexpected errors, and probably eventually a crash. It will only happen maybe 1/1000 times you run your program, and possibly nothing bad will be apparent until several minutes after the actual error occurred. Very hard to debug.
Follow their advice and don't try it.
Did you pull the objects out of the database, or did you also try to access properties? That is when faults get dealt with...
It is very likely that at some point, your code will crash.
精彩评论