将dispatch_sync调用转换为dispatch_async调用 [英] dispatch_sync call into a dispatch_async call

查看:85
本文介绍了将dispatch_sync调用转换为dispatch_async调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此代码的行为有疑问:

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

我希望从这些行中获得step1 -> step3 -> step2作为输出,但我仅获得step1.

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

如果我用dispatch_async更改了dispatch_sync,它可以按预期工作,请问dispatch_sync进入dispatch_async调用会产生这种问题吗?

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 ?

答案后编辑----------------

这种情况会造成死锁:

您可以检查已接受的答案以对此情况进行说明,并检查此链接以获取文档

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

推荐答案

那是一个僵局.

dispatch_sync调用将一直等到queue可用,然后再运行其块并返回,但直到dispatch_async完成后该调用才可用,因此它将坐在那里旋转以等待调用dispatch_sync

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.

这篇关于将dispatch_sync调用转换为dispatch_async调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆