为什么同步代码块总是在主线程上调用?

Why a sync block of code always call on main thread?

我用 DispatchQueue 做了简单的测试:

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

打印出:

Main thread

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

因为实际上不需要。您正在使用 sync 阻塞主线程。 iOS 选择只在主线程上执行它,而不是费心切换到(后台队列的)后台线程,因为它并不重要,因为主线程无论如何都会被阻塞。

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

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

问题是你问错了问题。不要混淆队列和线程。使用队列并让 它们 根据需要重新调整线程。这正是我们排队的原因!您不必担心您正在使用的线程只需要知道你在右边队列,你可以这样找到:

let q = DispatchQueue.global(qos: .background)
q.sync {
    dispatchPrecondition(condition: .onQueue(q))
    print("it's okay! we're on the right queue") // yep
}