使用dispatch_sync进行死锁 [英] Deadlock with dispatch_sync

查看:155
本文介绍了使用dispatch_sync进行死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
    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文档

I am getting a deadlock here. According to Apple documentation


dispatch_sync:将一个块提交到调度队列以执行同步
。与dispatch_async不同,这个函数不会返回,直到
块结束。调用此函数并定位
当前队列会导致死锁。。

"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 ,然后我执行内部 ditpatch_sync 在不同的队列中,即`main_queue。

However, I do the outer dispatch_sync on myQueue and then I do inner ditpatch_sync on a different queue which is `main_queue.

无法找出死锁的原因。任何评论/帮助都在这里赞赏。

Can not find out the reason for the deadlock. Any comments/help are appreciated here.

推荐答案

如果你像这样调度_sync到myQueue并且调用发生在主线程上,那么如果可能的话,dispatch_sync将在那里执行块,而不是像dispatch_async那样在新的工作线程上执行。你无法保证为你的队列获得一个单独的工作线程。

If you dispatch_sync to myQueue like that and the call happens on the main thread, then dispatch_sync will, if possible, execute the block right there and not on a new worker thread like dispatch_async would. You're not guaranteed to get a separate worker thread for your queue.

然后该块在主线程上运行,直到它到达你的第二个dispatch_sync调用,这恰好是目标主队列。该队列无法提供服务,因为已经有一个块在运行,这就是你最终陷入僵局的地方。

The block then runs on the main thread until it hits your second dispatch_sync call, which happens to target the main queue. That queue can't be serviced, since there's already a block running on it, and that's where you end up in a deadlock.

如果这是你的问题,即第一个dispatch_sync确实来自主线程,那么你应该切换到dispatch_async。您不希望使用长时间运行的EXTREME PROCESSING操作来阻止主线程。

If that's your problem, i.e. the first dispatch_sync is indeed coming from the main thread, then you should switch to dispatch_async. You wouldn't want to block the main thread with the long-running "EXTREME PROCESSING" operation.

这篇关于使用dispatch_sync进行死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆