有没有办法限制 GCD 在我的应用程序中生成的线程数?

Is there a way to limit the number of threads spawned by GCD in my application?

我通过对 this question 的响应知道生成的最大线程数不能超过 66。但是有没有办法将线程数限制为用户定义的值?

根据我在各种情况下使用 GCD 的经验,我认为这是不可能的。

说,理解这一点非常重要,通过使用 GCD,你产生 queues,而不是 threads。每当您的代码调用创建队列时,GCD 子系统就会依次检查 OS 条件并寻找可用资源。然后根据这些条件在后台创建新线程——按照顺序和分配的资源,不受您的控制。官方文档中对此有明确的解释:

When it comes to adding concurrency to an application, dispatch queues provide several advantages over threads. The most direct advantage is the simplicity of the work-queue programming model. With threads, you have to write code both for the work you want to perform and for the creation and management of the threads themselves. Dispatch queues let you focus on the work you actually want to perform without having to worry about the thread creation and management. Instead, the system handles all of the thread creation and management for you. The advantage is that the system is able to manage threads much more efficiently than any single application ever could. The system can scale the number of threads dynamically based on the available resources and current system conditions. In addition, the system is usually able to start running your task more quickly than you could if you created the thread yourself.

Source: Dispatch Queues

您无法使用 GCD 控制资源消耗,例如设置某种阈值。 GCD 是对低级事物(例如线程)的高级抽象,它会为您管理它。

您可能 影响 应用程序中特定任务应占用多少资源的唯一方法是设置其 QoS (Quality of Service) class(以前称为简单地作为优先级,扩展到更复杂的概念)。简而言之,您可以 class 根据任务的重要性在您的应用程序中分配任务,这样可以帮助 GCD 和您的应用程序提高资源和电池效率。在具有大量并发使用的复杂应用程序中,强烈鼓励使用它。 然而,即使如此,这种来自开发者端的规定也有其局限性,最终没有达到控制线程创建的目标:

Apps and operations compete to use finite resources—CPU, memory, network interfaces, and so on. In order to remain responsive and efficient, the system needs to prioritize tasks and make intelligent decisions about when to execute them.

Work that directly impacts the user, such as UI updates, is extremely important and takes precedence over other work that may be occurring in the background. This higher priority work often uses more energy, as it may require substantial and immediate access to system resources.

As a developer, you can help the system prioritize more effectively by categorizing your app’s work, based on importance. Even if you’ve implemented other efficiency measures, such as deferring work until an optimal time, the system still needs to perform some level of prioritization. Therefore, it is still important to categorize the work your app performs.

Source: Prioritize Work with Quality of Service Classes

总而言之,如果您有意控制线程,请不要使用 GCD。使用低级编程技术并自行管理它们。如果您使用GCD,那么您同意将这种责任交给GCD。