使核心数据线程安全

时间:2012-05-15 03:20:56

标签: ios multithreading core-data concurrency

长话短说,我厌倦了与NSManagedObjectContext相关的荒谬并发规则(或者更确切地说,如果你试图共享一个NSManagedObjectContext,它完全缺乏对并发的支持以及爆炸的倾向或做其他不正确的事情。 {1}}跨线程),我正在尝试实现线程安全的变体。

基本上我所做的是创建一个子类来跟踪它创建的线程,然后将所有方法调用映射回该线程。这样做的机制有点令人费解,但问题的关键在于我有一些辅助方法,如:

- (NSInvocation*) invocationWithSelector:(SEL)selector {
    //creates an NSInvocation for the given selector
    NSMethodSignature* sig = [self methodSignatureForSelector:selector];    
    NSInvocation* call = [NSInvocation invocationWithMethodSignature:sig];
    [call retainArguments];
    call.target = self;

    call.selector = selector;

    return call;
}

- (void) runInvocationOnContextThread:(NSInvocation*)invocation {
    //performs an NSInvocation on the thread associated with this context
    NSThread* currentThread = [NSThread currentThread];
    if (currentThread != myThread) {
        //call over to the correct thread
        [self performSelector:@selector(runInvocationOnContextThread:) onThread:myThread withObject:invocation waitUntilDone:YES];
    }
    else {
        //we're okay to invoke the target now
        [invocation invoke];
    }
}


- (id) runInvocationReturningObject:(NSInvocation*) call {
    //returns object types only
    [self runInvocationOnContextThread:call];

    //now grab the return value
    __unsafe_unretained id result = nil;
    [call getReturnValue:&result];
    return result;
}

...然后子类按照以下模式实现NSManagedContext接口:

- (NSArray*) executeFetchRequest:(NSFetchRequest *)request error:(NSError *__autoreleasing *)error {
    //if we're on the context thread, we can directly call the superclass
    if ([NSThread currentThread] == myThread) {
        return [super executeFetchRequest:request error:error];
    }

    //if we get here, we need to remap the invocation back to the context thread
    @synchronized(self) {
        //execute the call on the correct thread for this context
        NSInvocation* call = [self invocationWithSelector:@selector(executeFetchRequest:error:) andArg:request];
        [call setArgument:&error atIndex:3];
        return [self runInvocationReturningObject:call];
    }
}

...然后我用一些类似的代码测试它:

- (void) testContext:(NSManagedObjectContext*) context {
    while (true) {
        if (arc4random() % 2 == 0) {
            //insert
            MyEntity* obj = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" inManagedObjectContext:context];
            obj.someNumber = [NSNumber numberWithDouble:1.0];
            obj.anotherNumber = [NSNumber numberWithDouble:1.0];
            obj.aString = [NSString stringWithFormat:@"%d", arc4random()];

            [context refreshObject:obj mergeChanges:YES];
            [context save:nil];
        }
        else {
            //delete
            NSArray* others = [context fetchObjectsForEntityName:@"MyEntity"];
            if ([others lastObject]) {
                MyEntity* target = [others lastObject];
                [context deleteObject:target];
                [context save:nil];
            }
        }
        [NSThread sleepForTimeInterval:0.1];
    }
}

基本上,我启动了一些针对上述入口点的线程,他们随机创建和删除实体。这几乎按照应有的方式运作。

问题在于,在调用EXC_BAD_ACCESS时,每个线程中的一个线程都会获得obj.<field> = <value>;。我不清楚问题是什么,因为如果我在调试器中打印obj,一切看起来都不错。关于问题可能是什么的任何建议(除了Apple建议不要对NSManagedObjectContext进行子类化)以及如何修复它?

P.S。我知道GCD和NSOperationQueue以及通常用来“解决”这个问题的其他技术。这些都没有提供我想要的东西。我正在寻找的是一个NSManagedObjectContext,它可以被任意数量的线程自由,安全地直接使用,无需任何外部同步即可查看和更改应用程序状态。

3 个答案:

答案 0 :(得分:7)

正如noa正确指出的那样,问题在于虽然我已经使NSManagedObjectContext线程安全,但我没有将NSManagedObject实例本身设备为线程安全的。线程安全上下文和非线程安全实体之间的交互是造成我的定期崩溃的原因。

如果有人感兴趣,我创建了一个线程安全的NSManagedObject子类,通过注入我自己的setter方法来代替Core Data通常生成的那些(某些)。这是使用以下代码完成的:

//implement these so that we know what thread our associated context is on
- (void) awakeFromInsert {
    myThread = [NSThread currentThread];
}
- (void) awakeFromFetch {
    myThread = [NSThread currentThread];
}

//helper for re-invoking the dynamic setter method, because the NSInvocation requires a @selector and dynamicSetter() isn't one
- (void) recallDynamicSetter:(SEL)sel withObject:(id)obj {
    dynamicSetter(self, sel, obj);
}

//mapping invocations back to the context thread
- (void) runInvocationOnCorrectThread:(NSInvocation*)call {
    if (! [self myThread] || [NSThread currentThread] == [self myThread]) {
        //okay to invoke
        [call invoke];
    }
    else {
        //remap to the correct thread
        [self performSelector:@selector(runInvocationOnCorrectThread:) onThread:myThread withObject:call waitUntilDone:YES];
    }
}

//magic!  perform the same operations that the Core Data generated setter would, but only after ensuring we are on the correct thread
void dynamicSetter(id self, SEL _cmd, id obj) {
    if (! [self myThread] || [NSThread currentThread] == [self myThread]) {
        //okay to execute
        //XXX:  clunky way to get the property name, but meh...
        NSString* targetSel = NSStringFromSelector(_cmd);
        NSString* propertyNameUpper = [targetSel substringFromIndex:3];  //remove the 'set'
        NSString* firstLetter = [[propertyNameUpper substringToIndex:1] lowercaseString];
        NSString* propertyName = [NSString stringWithFormat:@"%@%@", firstLetter, [propertyNameUpper substringFromIndex:1]];
        propertyName = [propertyName substringToIndex:[propertyName length] - 1];

        //NSLog(@"Setting property:  name=%@", propertyName);

        [self willChangeValueForKey:propertyName];
        [self setPrimitiveValue:obj forKey:propertyName];
        [self didChangeValueForKey:propertyName];

    }
    else {
        //call back on the correct thread
        NSMethodSignature* sig = [self methodSignatureForSelector:@selector(recallDynamicSetter:withObject:)];
        NSInvocation* call = [NSInvocation invocationWithMethodSignature:sig];
        [call retainArguments];
        call.target = self;
        call.selector = @selector(recallDynamicSetter:withObject:);
        [call setArgument:&_cmd atIndex:2];
        [call setArgument:&obj atIndex:3];

        [self runInvocationOnCorrectThread:call];
    }
}

//bootstrapping the magic; watch for setters and override each one we see
+ (BOOL) resolveInstanceMethod:(SEL)sel {
    NSString* targetSel = NSStringFromSelector(sel);
    if ([targetSel startsWith:@"set"] && ! [targetSel contains:@"Primitive"]) {
        NSLog(@"Overriding selector:  %@", targetSel);
        class_addMethod([self class], sel, (IMP)dynamicSetter, "v@:@");
        return YES;
    }

    return [super resolveInstanceMethod:sel];
}

这与我的线程安全上下文实现一起解决了问题并得到了我想要的东西;一个线程安全的上下文,我可以传递给我想要的任何人,而不必担心后果。

当然,这不是一个防弹解决方案,因为我至少已经确定了以下限制:

/* Also note that using this tool carries several small caveats:
 *
 *      1.  All entities in the data model MUST inherit from 'ThreadSafeManagedObject'.  Inheriting directly from 
 *          NSManagedObject is not acceptable and WILL crash the app.  Either every entity is thread-safe, or none 
 *          of them are.
 *
 *      2.  You MUST use 'ThreadSafeContext' instead of 'NSManagedObjectContext'.  If you don't do this then there 
 *          is no point in using 'ThreadSafeManagedObject' (and vice-versa).  You need to use the two classes together, 
 *          or not at all.  Note that to "use" ThreadSafeContext, all you have to do is replace every [[NSManagedObjectContext alloc] init]
 *          with an [[ThreadSafeContext alloc] init].
 *
 *      3.  You SHOULD NOT give any 'ThreadSafeManagedObject' a custom setter implementation.  If you implement a custom 
 *          setter, then ThreadSafeManagedObject will not be able to synchronize it, and the data model will no longer 
 *          be thread-safe.  Note that it is technically possible to work around this, by replicating the synchronization
 *          logic on a one-off basis for each custom setter added.
 *
 *      4.  You SHOULD NOT add any additional @dynamic properties to your object, or any additional custom methods named
 *          like 'set...'.  If you do the 'ThreadSafeManagedObject' superclass may attempt to override and synchronize 
 *          your implementation.
 *
 *      5.  If you implement 'awakeFromInsert' or 'awakeFromFetch' in your data model class(es), thne you MUST call 
 *          the superclass implementation of these methods before you do anything else.
 *
 *      6.  You SHOULD NOT directly invoke 'setPrimitiveValue:forKey:' or any variant thereof.  
 *
 */

但是,对于大多数典型的中小型项目,我认为线程安全数据层的好处明显超过了这些限制。

答案 1 :(得分:3)

为什么不使用提供的并发类型之一实例化您的上下文,并利用performBlock / performBlockAndWait?

这实现了必要的线程限制,必须通过实现Core Data的访问器方法来实现。正如您很快就会发现的那样,对于您的用户来说,要么是正确的,要么结束会非常痛苦。

答案 2 :(得分:1)

Bart Jacobs的一个很棒的教程,题为:Core Data from Scratch: Concurrency适用于那些需要iOS 5.0或更高版本和/或Lion或更高版本的优雅解决方案的人。详细描述了两种方法,更优雅的解决方案涉及父/子管理对象上下文。