关于调用dispatch_queue_t和dispatch_sync
问题描述:
为什么需要代码if (dispatch_get_current_queue() == socketQueue)
?为什么我们不能直接使用dispatch_sync(socketQueue, block)
???
Why the code if (dispatch_get_current_queue() == socketQueue)
is needed? why can't we just use dispatch_sync(socketQueue, block)
directly???
提前谢谢!
- (BOOL)isConnected
{
__block BOOL result = NO;
dispatch_block_t block = ^{
result = (flags & kConnected) ? YES : NO;
};
if (dispatch_get_current_queue() == socketQueue)
block();
else
dispatch_sync(socketQueue, block);
return result;
}
顺便说一句,代码来自 XMPPFramework
BTW, the code is from XMPPFramework
答
您无法调用dispatch_sync
来调度当前串行队列上的块,因为这将导致死锁. Dispatch_sync会等到该块完成执行,但是它永远不会在当前块完成运行之前开始运行.
You cannot call dispatch_sync
to schedule blocks on the current serial queue since this will deadlock. Dispatch_sync waits until the block finished executing, but it will never start to run before the current block finished running.