dispatch_sync call into a dispatch_async call

给你一囗甜甜゛ 提交于 2020-01-01 05:19:10

问题


I get some doubts about behavior of this code :

dispatch_async(queue, ^{
    sleep(2);
    NSLog(@"step1");

    dispatch_sync(queue, ^{
        sleep(3);
        NSLog(@"step 2");
    });

    NSLog(@"step 3");
});

From these rows i expected to get as output step1 -> step3 -> step2 but i obtain only step1.

If i change dispatch_sync with dispatch_async it works as expected, Does dispatch_sync into a dispatch_async call create this kind of problem ?

Edit after answers ----------------

This case create a deadlock:

You can check accepted answer to have explanation of this situation and check this link for documentation http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_async.3.html


回答1:


That's a deadlock.

The dispatch_sync call will be waiting until queue is available before running its block and returning but that won't be available until the dispatch_async has finished so it will just sit there spinning waiting to call dispatch_sync.




回答2:


As mentioned by @mattjgalloway, it is a deadlock.

Apple's own documentation mentions the problem here: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_async.3.html (see "RECURSIVE LOCKS"). It is discussed in the context of recursive locks, but the principle is the same.



来源:https://stackoverflow.com/questions/8668585/dispatch-sync-call-into-a-dispatch-async-call

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