在当前队列上同步分派 [英] Sync dispatch on current queue
问题描述
我知道你可能会发现这是一个奇怪的问题,但我只是在学习GCD,我想完全了解它的所有方面。所以这里是:
I know you might find this an odd question, but I'm just learning GCD and I want to fully understand all its aspects. So here it is:
是否有任何理由在CURRENT QUEUE上分派任务SYNC?
Is there ever any reason to dispatch a task SYNC on the CURRENT QUEUE?
例如:
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(...);
dispatch_async(concurrentQueue, ^{
//this is work task 0
//first do something here, then suddenly:
dispatch_sync(concurrentQueue, ^{
//work task 1
});
//continue work task 0
});
我理解一件事:if代替 concurrentQueue
我使用 serial 队列,然后我在该串行队列上得到死锁,因为工作任务1
>工作任务0 完成(由于保证执行顺序的串行队列),并且同时工作任务0
无法继续执行,因为它等待SYNC dispath函数返回(请纠正我,如果我错了,这将使我一个总的noob)。
I understand one thing: if instead of concurrentQueue
I use a serial queue, then I get a deadlock on that serial queue, because work task 1
cannot start until the work task 0
is finished (because of the serial queue that guarantees order of execution), and in the same time work task 0
cannot continue its execution because it waits for the SYNC dispath function to return (please correct me if I'm wrong, that would make me a total noob).
回到原始思想,上述代码和同一代码之间有什么区别,而不是调用 dispatch_sync
函数,我只需写工作任务1
代码直接?
So coming back to the original idea, is there any difference whatsoever between the code above and the same code where instead of calling the dispatch_sync
function I simply write work task 1
code directly?
推荐答案
否。我不能想到在你已经在同一并发队列上 dispatch_sync
的原因。如果你这样做,GCD将立即调用你的块,在线,在同一个线程,就好像你直接调用。 (我检查过。)正如你所指出的,在一个串行队列上这样做会使你死锁。
No. I can't think of a reason to ever dispatch_sync
on the same concurrent queue you're already on. If you do that, GCD will just immediately invoke your block, in-line, on the same thread, as if you had called it directly. (I checked.) And as you pointed out, doing that on a serial queue will deadlock you.
这篇关于在当前队列上同步分派的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!