ios – 如何在Grand Central Dispatch中创建一个僵局?

在苹果文档中,它说:

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

这里很清楚,外部和内部块在同一个队列上运行.大多数情况下会发生这种情况的地方,dispatch_sync的调用者的队列不太明显.这通常发生在(深入)嵌套的堆栈中,您正在某些类中执行代码,这些代码最初是在某个队列中启动的,而且您偶然会将dispatch_sync调用到同一个队列.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...