Skip navigation.
 
mlBasic Coredata / threading question
FROM : Walt Horat
DATE : Fri Apr 06 21:26:02 2007

I have an application that keeps a large model. The app fires off a 
number of network queries in parallel - each of these is fired on a 
separate thread. Each of these threads needs to access the model when 
the response returns, and execute a fetch which will require coredata 
to touch nearly every object in the model.

It seems that if each thread is given its own managed object context, 
the app will have N copies of the model all in memory at the same 
time - this does not sound like a good strategy for large datasets.

As a solution, I have tried implementing each thread so as to send a 
dictionary of non-managed objects over to the main thread (using 
NSObject performSelectorOnMainThread) to actually do the work. This 
seems to work, until the next time the app. tries to save the model - 
it deadlocks inside of the call to save. It is unclear whom is 
locking what as I can see that all of the network threads have 
already completed.

I am considering trying to simplify the design doing what I am told 
is bad - to have the threads share the same managed object context. 
It seems to my limited understanding of core data, that by using fine 
grained locking, this could be made to work.

I am considering re-coding all the core data accessors as follows:

- (NSNumber *)foo
{
    NSNumber * tmpValue;

    [[self managedObjectContext] lock];
    [self willAccessValueForKey: @"foo"];
    tmpValue = [self primitiveValueForKey: @"foo"];
    [self didAccessValueForKey: @"foo"];
    [[self managedObjectContext] unlock];

    return tmpValue;
}

- (void)setFoo:(NSNumber *)value
{
    [[self managedObjectContext] lock];
    [self willChangeValueForKey: @"foo"];
    [self setPrimitiveValue: value forKey: @"foo"];
    [self didChangeValueForKey: @"foo"];
    [[self managedObjectContext] unlock];
}

It seems that this should have the effect of serializing all access 
to the model, as whenever any thread dips into the model through 
managed object accessor methods it will lock (or block) appropriately.

Any advice, suggestions or strategies greatly appreciated.

Regards,


Walt
        at soundflavor dot com
-----

Related mailsAuthorDate
mlBasic Coredata / threading question Walt Horat Apr 6, 21:26
mlRe: Basic Coredata / threading question Scott Stevenson Apr 7, 09:02
mlRe: Basic Coredata / threading question Jim Correia Apr 7, 19:39
mlre: Basic Coredata / threading question Ben Trumbull Apr 8, 01:03