且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS开发中'thread'和'queue'有什么区别?

更新时间:2021-09-01 00:25:55

在您阅读我的回答之前,您可能需要考虑阅读本文 - 远离线程

Before you read my answer you might want to consider reading this - Migrating away from Threads

我保持讨论的理论性,因为您的问题没有任何代码示例。这两种结构都是提高应用响应能力所必需的。可用性。

I am keeping the discussion theoretical as your question does not have any code samples. Both these constructs are required for increasing app responsiveness & usability.

消息队列是一种数据结构,用于从发送消息到收件人检索并执行操作之前保留消息他们。通常,队列被用作连接生成者(数据)和生成的方式。消费者(数据)。

A message queue is a data structure for holding messages from the time they're sent until the time the receiver retrieves and acts on them. Generally queues are used as a way to 'connect' producers (of data) & consumers (of data).

线程池是执行某种处理的线程池。线程池通常会附加一些线程安全队列(引用消息队列),以允许您排队要完成的作业。这里的队列通常被称为任务队列。

A thread pool is a pool of threads that do some sort of processing. A thread pool will normally have some sort of thread-safe queue (refer message queue) attached to allow you to queue up jobs to be done. Here the queue would usually be termed 'task-queue'.

因此,线程池可能存在于生产者端(生成数据)或消费者端(处理数据)。而传递数据的方式是通过队列。为什么需要这个中间人 -

So in a way thread pool could exist at your producer end (generating data) or consumer end (processing the data). And the way to 'pass' that data would be through queues. Why the need for this "middleman" -


  1. 它解耦系统。生产者不了解消费者和消费者。反之亦然。

  2. 如果生产者数据出现峰值,消费者不会被数据轰炸。队列长度会增加,但消费者是安全的。

示例:

在iOS中主线程,也称为UI线程,非常重要,因为它负责将事件分派给适当的小部件,这包括绘图事件,基本上是用户看到的UI和&交互。

In iOS the main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widget and this includes the drawing events, basically the UI that the user sees & interacts.

如果触摸屏幕上的按钮,UI线程会将触摸事件发送给应用程序,然后应用程序会设置其按下状态并向事件发送请求队列即可。 UI线程将请求出列并通知窗口小部件重绘自己。

If you touch a button on screen, the UI thread dispatches the touch event to the app, which in turn sets its pressed state and posts an request to the event queue. The UI thread dequeues the request and notifies the widget to redraw itself.