Sync dispatch on current queue

こ雲淡風輕ζ 提交于 2019-12-04 04:05:25

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.

Assume this queue for all examples:

dispatch_queue_t queue = dispatch_queue_create(“com.somecompany.queue”, nil);

Situation 1 - OK

dispatch_async(queue, ^{
    [self goDoSomethingLongAndInvolved];
    dispatch_async(queue, ^{
        NSLog(@"Situation 1");
    });
});

Situation 2 - Not OK! Deadlock!

dispatch_sync(queue, ^{
    [self goDoSomethingLongAndInvolved];
    dispatch_sync(queue, ^{
        NSLog(@"Situation 2”); // NOT REACHED!  DEADLOCK!
    });
});

Situation 3 - Not OK! Deadlock!

dispatch_async(queue, ^{
    [self goDoSomethingLongAndInvolved];
    dispatch_sync(queue, ^{
        NSLog(@"Situation 3"); // NOT REACHED!  DEADLOCK!
    });
});

Situation 4 - OK

dispatch_sync(queue, ^{
    [self goDoSomethingLongAndInvolved];
    dispatch_async(queue, ^{
        NSLog(@"Situation 4");
    });
});

Basically dispatch_sync does not like to be on the inside.

Only dispatch_asyncs can go inside.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!