为什么同步代码块总是在主线程上调用? [英] Why a sync block of code always call on main thread?

查看:98
本文介绍了为什么同步代码块总是在主线程上调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用DispatchQueue做了简单测试:

I did the simple test with DispatchQueue:

DispatchQueue.global(qos: .background).sync {
  if Thread.isMainThread {
    print("Main thread")
  }
}

它打印出来:

Main thread

为什么此代码在主线程上执行?应该在后台线程上执行(它已添加到后台队列中),对吧?

Why does this code execute on the main thread? It should be performed on a background thread (it was added to a background queue), right?

推荐答案

因为它没有实际上必须。您正在使用同步功能来阻止主线程。 iOS选择只在主线程上执行它,而不用费心切换到(后台队列的)后台线程,因为这实际上并不重要,因为无论如何主线程都被阻塞了。

Because it doesn't actually have to. You're blocking the main thread by using sync. iOS is choosing to just execute it on the main thread instead of bothering to switch to a background thread (of a background queue) as it doesn't really matter due to main thread being blocked anyways.

有关同步功能的Apple文档(和快速帮助)包括以下行:

Apple's docs (and quickhelp) on the sync function include the line:


作为优化,此函数调用

As an optimization, this function invokes the block on the current thread when possible.

这篇关于为什么同步代码块总是在主线程上调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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