gpt4 book ai didi

ios - 如何在 Grand Central Dispatch 中创建死锁?

转载 作者:IT王子 更新时间:2023-10-29 08:13:03 26 4
gpt4 key购买 nike

在 Apple 文档中,它说:

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.

您如何编写代码来做到这一点?

最佳答案

某个队列上的故意死锁:

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

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

关于ios - 如何在 Grand Central Dispatch 中创建死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15381209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com