如何在Grand Central Dispatch中创建死锁? [英] How do I create a deadlock in Grand Central Dispatch?

查看:83
本文介绍了如何在Grand Central Dispatch中创建死锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Apple文档中,它说:

In Apple docs, it says:


重要提示:永远不要从任务中调用dispatch_sync或dispatch_sync_f
函数这是在同一个队列中执行,你计划传递给函数
。这对于
串行队列尤其重要,这些串行队列保证死锁,但对于并发队列也应避免

Important: You should never call the dispatch_sync or dispatch_sync_f function from a task that is executing in the same queue that you are planning to pass to the function. This is particularly important for serial queues, which are guaranteed to deadlock, but should also be avoided for concurrent queues.

你如何编写代码才能做到这一点?

How do you write the code to do exactly this?

推荐答案

特定队列上的故意死锁:

An intentional deadlock on a certain queue:

dispatch_queue_t queue = dispatch_queue_create("my.label", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
    dispatch_sync(queue, ^{
        // outer block is waiting for this inner block to complete,
        // inner block won't start before outer block finishes
        // => deadlock
    });

    // this will never be reached
}); 

这里很明显外部和内部块在同一队列上运行。发生这种情况的大多数情况是在 dispatch_sync 的调用者正在运行的队列不太明显的地方。这通常发生在(深度)嵌套堆栈中,您在某个类中执行最初在某个队列上启动的代码,并且不小心您将 dispatch_sync 调用到相同的队列。

It's clear here that the outer and inner blocks are operating on the same queue. Most cases where this will occur is in places where it's less obvious what queue the caller of the dispatch_sync is operating on. This usually occurs in a (deeply) nested stack where you're executing code in some class that was originally launched on a certain queue, and by accident you call a dispatch_sync to the same queue.

这篇关于如何在Grand Central Dispatch中创建死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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