{
dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_sync(myQueue, ^{
//Do EXTREME PROCESSING!!!
for (int i = 0; i< 100; i++) {
[NSThread sleepForTimeInterval:.05];
NSLog(@"%i", i);
}
dispatch_sync(dispatch_get_main_queue(), ^{
[self updateLabelWhenBackgroundDone];
});
});
}
我在这里陷入僵局。根据 Apple 文档
"dispatch_sync": "Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async, this function does not return until the block has finished. Calling this function and targeting the current queue results in deadlock.".
但是,我在 myQueue
上执行外部 dispatch_sync
,然后在另一个队列“main_queue”上执行内部 ditpatch_sync
。
找不到死锁的原因。在此感谢任何评论/帮助。
最佳答案
如果您像那样将 dispatch_sync 发送到 myQueue 并且调用发生在主线程上,那么 dispatch_sync 将在可能的情况下就在那里执行 block ,而不是像 dispatch_async 那样在新的工作线程上执行。您不能保证为您的队列获得一个单独的工作线程。
然后该 block 在主线程上运行,直到它遇到您的第二个 dispatch_sync 调用,该调用恰好以主队列为目标。无法为该队列提供服务,因为上面已经有一个 block 在运行,这就是您最终陷入死锁的地方。
如果那是你的问题,即第一个 dispatch_sync 确实来自主线程,那么你应该切换到 dispatch_async。您不希望使用长时间运行的“EXTREME PROCESSING”操作来阻塞主线程。
关于iphone - dispatch_sync 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297118/