ios - 有没有办法限制我的应用程序中GCD产生的线程数?

标签 ios multithreading grand-central-dispatch

我知道通过响应this question产生的最大线程数不能超过66。但是,是否有一种方法可以将线程数限制为用户定义的值?

最佳答案

根据我的经验以及在各种情况下与GCD的合作,我相信这是不可能的。

话虽如此,理解这一点非常重要,通过使用GCD,可以生成队列,而不是线程。每当从您的代码发出创建队列的调用时,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)类(以前简称为优先级,扩展为更复杂的概念)。简而言之,您可以基于任务的重要性对应用程序中的任务进行分类,从而帮助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。

关于ios - 有没有办法限制我的应用程序中GCD产生的线程数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395957/

相关文章:

java - 在匿名线程中使用最终变量

ios - 从异步回调传递数据

objective-c - 在 ARC 之后,我应该为调度队列使用什么属性?

objective-c - 从触摸点获取单个像素

iOS:SDK iOS7 和 XCode 4.6.3

ios - 将两个核心数据结果加入 1 个 NSDictionary

c++ - 在 C++ 中线程化以保持两个函数并行运行

ios - 覆盖 initWithEntity :insertIntoManagedObjectContext:

c# - 如何在可由另一个线程更改的 IEnumerable 上安全地调用 Count(Func)?

ios - 监视文件更改时打开太多文件