GCD:线程只有两种类型吗?主线程和后台线程

GCD: does thread only has two types? main thread and background thread

上下文:

据我了解,Main DispatchQueue 仅在 Main Thread 上调度任务,主要用于 UI。

然而 Main Thread 也可以被非主要的 DispatchQueue 使用。

Apple QOS 优先处理任务:

User Interactive: Work that happens on the main thread, such as animations or drawing operations.

User Initiated: Work that the user kicks off and should yield immediate results. This work must be completed for the user to continue.

Utility: Work that may take a bit and doesn’t need to finish right away. Analogous to progress bars and importing data.

Background: This work isn’t visible to the user. Backups, syncs, indexing, etc.

我的问题是:

0,如题所述,线程是否只包含Main ThreadBackground Thread两种类型?

1,Background Thread是否意味着所有执行的任务都不会阻塞UI?

2、既然提到了User Interactive是任务会在主线程执行的优先级,以避免UI滞后,是否意味着所有其他类型:User Initiated, Utility, Background 将确保 Background Thread 不会阻塞 UI?

3、来自link、。 它提到了创建 Dispatch Queue 的几种不同方法,有些是并发的,有些是串行的。它还提到通过为 defaultbackground 分配 QOS,它保证 Queue 访问 background threads。但是在 SerialConcurrent 中没有提到这样的事情。我想知道这些是否正确?

你问:

does thread only contain 2 types, which are Main Thread and Background Thread?

我不确定我是否会将它们描述为不同的“类型”,但从应用程序开发人员的角度来看,是的,有一个“主”线程,专用于 UI,主要运行 循环等,还有所有其他线程,根据定义,它们是“后台”线程。

我们总是要小心 运行 主队列(即不要 运行 任何可能阻塞该线程并有效阻塞 UI ).在实践中,我们希望避免在主队列上做任何可能阻塞它最多几毫秒的事情。

does Background Thread mean that all the tasks executed won't block the UI?

有效,是的。但我们处理的是设备上的有限资源,因此开发人员必须审慎行事。例如,对于我们的后台任务,我们希望使用与该队列正在执行的操作相称的 QoS。或者,如果将某些任务并行化,则应注意限制并发度。但是如果一个人对系统资源的使用是明智的,并且将阻塞任务从主队列中移除,那么这可以确保响应迅速 UI.

底线,是的,如果您有一些代码会阻塞其 运行 所在的线程(例如,它在计算上很昂贵,它具有信号量或调度组 wait 等阻塞调用.),您通常会 运行 在后台线程上执行此操作以避免阻塞主队列。

Since it mentions that the User Interactive is the priority that the task will be executed on the main thread to avoid UI lags, does it mean all other types: User Initiated, Utility, Background will make sure to have Background Thread that does not block UI?

这些只是“服务质量”级别,它们只是队列的相对优先级。这不是“阻止 UI”或“不阻止”的问题,而只是 GCD 如何确定优先级和分配资源的问题。

From the link, How to create dispatch queue in Swift 3. It mentions a couple of different ways to create a Dispatch Queue, some are concurrent, some are serial...

... It also mentions that by assigning QOS with default or background, it guarantees that the Queue accesses to background threads...

这不太合理。或许您可以分享文档中的具体摘录,我们可以帮助您解读他们想说的内容。

... But nothing like this mentioned in the Serial and Concurrent. I wonder are those correct?

QoS 只是给定队列的优先级和资源问题。串行与并发只是一个队列是否一次仅限于单个线程的问题,或者它是否可以在需要和可用时利用多个线程。