0

I have this piece of code which is executed from different threads. I cant find wheres the deadlock. Maybe Im not undestanding how @syncronized works

@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()) );
}

Heres the traces when the app gets locked:

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?

As you can see Im syncronizing always on the same object.

Any ideas? Thanks a lot

4

1 回答 1

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];
于 2012-11-27T14:16:19.197 回答