【问题标题】:Locked up (dealock) in @syncrhonized [closed]在@syncrhonized 中锁定(死锁)[关闭]
【发布时间】:2012-11-27 12:35:07
【问题描述】:

我有这段从不同线程执行的代码。我找不到死锁在哪里。也许我不明白@syncronized 的工作原理

@synchronized(self) {
    NSLog(@"%@", self);
    NSLog(@"(%d) Aloha hermano blocked?" ,pthread_mach_thread_np(pthread_self()) );
    genres = [aContext executeFetchRequest:request error:&error];
    if (error != nil) {
        NSLog(@"Obj list fetch error: %@", error);
        exit(-1);
    }
    NSLog(@"(%d) Aloha hermano NO" ,pthread_mach_thread_np(pthread_self()) );
}

这是应用被锁定时的痕迹:

2012-11-27 13:28:05.141 (15143) Aloha hermano blocked?
2012-11-27 13:28:05.146 (15143) Aloha hermano NO
2012-11-27 13:28:05.152 <STBConnection_0_9: 0xc676000>
2012-11-27 13:28:05.155 (15143) Aloha hermano blocked?
2012-11-27 13:28:05.161 (15143) Aloha hermano NO
2012-11-27 13:28:05.168 <STBConnection_0_9: 0xc676000>
2012-11-27 13:28:05.171 (15143) Aloha hermano blocked?
2012-11-27 13:28:05.178 (15143) Aloha hermano NO
2012-11-27 13:28:05.185 <STBConnection_0_9: 0xc676000>
2012-11-27 13:28:05.191 (1799) Aloha hermano blocked?

如您所见,我总是在同一个对象上同步。

有什么想法吗?非常感谢

【问题讨论】:

    标签: objective-c cocoa-touch core-data mutex deadlock


    【解决方案1】:

    好的,我修复了它,问题是我使用了来自不同线程的相同 ManagebObjectContext。在这种情况下,Apple 文档说:

    如果您在线程之间共享托管对象上下文或持久存储协调器,则必须确保任何方法调用都是在线程安全范围内进行的。对于锁定,您应该在托管对象上下文和持久存储协调器上使用 NSLocking 方法,而不是实现自己的互斥锁。这些方法有助于向框架提供有关应用程序意图的上下文信息,也就是说,除了提供互斥体之外,它们还有助于确定操作集群的范围。

    所以,修复的代码如下:

    [aContext lock];
    genres = [aContext executeFetchRequest:request error:&error];
    if (error != nil) {
       NSLog(@"Obj list fetch error: %@", error);
       exit(-1);
    }
    [aContext unlock];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2011-05-29
      • 1970-01-01
      • 2019-11-17
      • 2020-01-18
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多