为什么在主队列上调用dispatch_sync()会阻塞主队列? [英] Why dispatch_sync( ) call on main queue is blocking the main queue?

查看:155
本文介绍了为什么在主队列上调用dispatch_sync()会阻塞主队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这不是一个强烈的问题,但我必须清楚这个概念。

I know this is not a strong question but I have to clear my mind on this concept.

我已定义 myBlock ,如下所示。

void(^myBlock)(void) = ^{
   for(int i = 0;i < 10 ; i++)
   {
       NSLog(@"%d and current queue = %@",i,[NSThread currentThread]);
   } 
};

现在使用 viewDidLoad 方法 dispatch_sync()方法独立于主队列,然后主队列被阻止。

Now In viewDidLoad method when I uses the dispatch_sync() method independently on main queue then the main queue gets blocked.

这是示例。

- (void)viewDidLoad
 {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue,myBlock);
 }

但是,当我使用相同的 dispatch_sync时( )主线程上的函数在一个 dispatch_async()块中,在并发队列中触发,然后主线程没有被阻塞。

But But, when I use the same dispatch_sync() function on main thread Inside a block of dispatch_async() function which is fired on concurrent queue then the main thread does not blocked.

以下是样本。

- (void)viewDidLoad
 {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue,^{  

        dispatch_sync(dispatch_get_main_queue(),myBlock);
    });
 }

我不清楚为什么会这样?为什么主线程在独立调用 dispatch_sync()时被阻止?

I am not clear why this is happening? Why main thread blocked when calling dispatch_sync() independently?

推荐答案

那里只是一个主要队列。在您的第一个示例中, viewDidLoad 正在其上运行。然后告诉 viewDidLoad 对要在主队列上运行的其他内容进行等待(即同步)。它们都不能同时在它上面。

There is only one main queue. In your first example, viewDidLoad is running on it. You then tell viewDidLoad to wait (i.e. "sync") on something else that's going to run on the main queue. They both can't be on it at exactly the same time.

在你的第二个例子中,它是被告知等待的并发队列。这不是问题,因为通过执行 dispatch_async viewWillLoad 放弃主队列并使其可用于您的块跑。

In your second example, it's the concurrent queue that's being told to wait. That's not a problem because by doing dispatch_async, viewWillLoad is giving up the main queue and making it available for your block to run.

这篇关于为什么在主队列上调用dispatch_sync()会阻塞主队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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