Execute code concurrently on multicore hardware by submitting work to dispatch queues managed by the system.
- 通過提交工作來調(diào)度系統(tǒng)管理的隊列太颤,在多核硬件上同時執(zhí)行代碼泡垃。
Overview
Dispatch comprises language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in macOS, iOS, watchOS, and tvOS.
- Dispatch包括語言功能,運行時庫和系統(tǒng)增強功能疫鹊,可為macOS咬摇,iOS伐蒂,watchOS和tvOS中多核硬件上的并發(fā)代碼執(zhí)行提供系統(tǒng),全面的改進肛鹏。
The BSD subsystem, Core Foundation, and Cocoa APIs have all been extended to use these enhancements to help both the system and your application to run faster, more efficiently, and with improved responsiveness. Consider how difficult it is for a single application to use multiple cores effectively, let alone doing it on different computers with different numbers of computing cores or in an environment with multiple applications competing for those cores. GCD, operating at the system level, can better accommodate the needs of all running applications, matching them to the available system resources in a balanced fashion.
- BSD子系統(tǒng)逸邦,Core Foundation和Cocoa API都已擴展為使用這些增強功能,以幫助系統(tǒng)和應用程序更快在扰,更高效地運行缕减,并提高響應速度。 考慮單個應用程序有效使用多個內(nèi)核的難度芒珠,更不用說在具有不同數(shù)量的計算內(nèi)核的不同計算機上或在多個應用程序競爭這些內(nèi)核的環(huán)境中執(zhí)行此操作桥狡。 在系統(tǒng)級別運行的GCD可以更好地滿足所有正在運行的應用程序的需求,并以平衡的方式將它們與可用的系統(tǒng)資源相匹配皱卓。
Managing Dispatch Queues
GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Work submitted to dispatch queues are executed on a pool of threads fully managed by the system. No guarantee is made as to the thread on which a task executes.
- GCD提供并管理應用程序可以以塊對象的形式提交任務的FIFO隊列总放。 提交到調(diào)度隊列的工作在完全由系統(tǒng)管理的線程池上執(zhí)行。 不保證任務執(zhí)行的線程好爬。
Synchronous and Asynchronous Execution
- 同步和異步執(zhí)行
Each work item can be executed either synchronously or asynchronously. When a work item is executed synchronously with the sync method, the program waits until execution finishes before the method call returns. When a work item is executed asynchronously with the async method, the method call returns immediately.
- 每個工作項可以同步或異步執(zhí)行。 當一個工作項用sync方法同步執(zhí)行時甥啄,在方法調(diào)用返回之前存炮,程序?qū)却钡焦ぷ黜棃?zhí)行完成。 當工作項使用async異步方法異步執(zhí)行時穆桂,方法調(diào)用立即返回宫盔。
Serial and Concurrent Queues
- 串行和并發(fā)隊列
A dispatch queue can be either serial, so that work items are executed one at a time, or it can be concurrent, so that work items are dequeued in order, but run all at once and can finish in any order. Both serial and concurrent queues process work items in first in, first-out (FIFO) order.
- 調(diào)度隊列可以是串行的,因此工作項可以一次執(zhí)行一個享完,也可以是并發(fā)的灼芭,因此工作項按順序出列,但可以一次性運行般又,并且可以按任何順序完成彼绷。 串行和并發(fā)隊列都以先進先出(FIFO)順序處理工作項。
System-Provided Queues
- 系統(tǒng)提供的隊列
When an app launches, the system automatically creates a special queue called the main queue. Work items enqueued to the main queue execute serially on your app’s main thread. You can access the main queue using the main type property.
- 當應用程序啟動時茴迁,系統(tǒng)會自動創(chuàng)建一個名為主隊列的特殊隊列寄悯。 排隊到主隊列的工作項在應用程序的主線程上串行執(zhí)行。 您可以使用main type屬性訪問主隊列堕义。
Important
Attempting to synchronously execute a work item on the main queue results in dead-lock.
- 嘗試在主隊列上同步執(zhí)行工作項會導致死鎖猜旬。
In addition to the serial main queue, the system also creates a number of global concurrent dispatch queues. You can access the global concurrent queue that best matches a specified quality of service (QoS) using the global(attributes:) type method.
- 除串行主隊列外,系統(tǒng)還會創(chuàng)建許多全局并發(fā)調(diào)度隊列倦卖。 您可以使用global(attributes :)類型方法訪問與指定服務質(zhì)量(QoS)最匹配的全局并發(fā)隊列洒擦。
DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.
- DispatchQueue管理工作項的執(zhí)行。 提交到隊列的每個工作項都在系統(tǒng)管理的線程池上處理怕膛。
DispatchSpecificKey
is a class that encapsulates keys that can be associated with a contextual value on a DispatchQueue
using the setSpecific<T>(key:value:) method, and accessed using the getSpecific<T>(key:) method.
- DispatchSpecificKey是一個類熟嫩,它使用setSpecific <T>(key:value :)方法封裝可以與DispatchQueue上的上下文值相關聯(lián)的鍵,并使用getSpecific <T>(key :)方法進行訪問嘉竟。
Managing Units of Work
Work items allow you to configure properties of individual units of work directly. They also allow you to address individual work units for the purposes of waiting for their completion, getting notified about their completion, and/or canceling them.
- 工作項允許您直接配置各個工作單元的屬性邦危。 它們還允許您處理單個工作單元,以便等待完成舍扰,獲得完成通知和/或取消它們倦蚪。
DispatchWorkItem
encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue
and within a DispatchGroup
. A DispatchWorkItem
can also be set as a DispatchSource
event, registration, or cancel handler.
- DispatchWorkItem封裝了可以執(zhí)行的工作。 可以將工作項分派到DispatchQueue和DispatchGroup中边苹。 DispatchWorkItem也可以設置為DispatchSource事件陵且,注冊或取消處理程序。
DispatchWorkItemFlags
are an option set that configure the behavior of a DispatchWorkItem value, including its quality of service class and whether to create a barrier or spawn a new detached thread.
- DispatchWorkItemFlags是一個選項集个束,用于配置DispatchWorkItem值的行為慕购,包括其服務質(zhì)量類以及是創(chuàng)建障礙還是生成新的分離線程。
Prioritizing Work and Specifying Quality of Service
- 優(yōu)先工作和指定服務質(zhì)量
DispatchQoS
encapsulates quality of service classes.
- DispatchQoS封裝了服務質(zhì)量類茬底。
DispatchQoS.QoSClass encapsulates quality of service classes.
- DispatchQoS.QoSClass封裝了服務質(zhì)量類沪悲。
Used to select the appropriate global concurrent queue.
- 用于選擇適當?shù)娜植l(fā)隊列。
Using Dispatch Groups
Grouping blocks allows for aggregate synchronization. Your application can submit multiple blocks and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.
- 分組塊允許聚合同步阱表。 您的應用程序可以提交多個塊并跟蹤它們是否完成殿如,即使它們可能在不同的隊列上運行贡珊。 在完成所有指定任務之前無法進行此操作時,此行為很有用涉馁。
DispatchGroup
allows for aggregate synchronization of work. You can use them to submit multiple different work items and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.
- DispatchGroup允許工作的聚合同步门岔。 您可以使用它們提交多個不同的工作項并跟蹤它們何時完成,即使它們可能在不同的隊列上運行烤送。 在完成所有指定任務之前無法進行此操作時寒随,此行為很有用。
Using Dispatch Semaphores
A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made.
- 調(diào)度信號量是傳統(tǒng)計數(shù)信號量的有效實現(xiàn)帮坚。 僅當需要阻止調(diào)用線程時妻往,Dispatch信號量才會調(diào)用內(nèi)核。 如果調(diào)用信號量不需要阻塞叶沛,則不進行內(nèi)核調(diào)用蒲讯。
DispatchSemaphore
provides an efficient implementation of a traditional counting semaphore, which can be used to control access to a resource across multiple execution contexts.
- DispatchSemaphore提供傳統(tǒng)計數(shù)信號量的有效實現(xiàn),可用于控制跨多個執(zhí)行上下文的資源訪問灰署。
Using Dispatch Data
DispatchData
objects manage a memory-based data buffer. The data buffer is exposed as a contiguous block of memory, but internally, it may be comprised of multiple, discontiguous blocks of memory.
- DispatchData對象管理基于內(nèi)存的數(shù)據(jù)緩沖區(qū)判帮。 數(shù)據(jù)緩沖區(qū)作為連續(xù)的內(nèi)存塊公開,但在內(nèi)部溉箕,它可能由多個不連續(xù)的內(nèi)存塊組成晦墙。
Using Dispatch Time
DispatchTime represents a point in time relative to the default clock with nanosecond precision. On Apple platforms, the default clock is based on the Mach absolute time unit.
- DispatchTime表示相對于具有納秒精度的默認時鐘的時間點。 在Apple平臺上肴茄,默認時鐘基于Mach絕對時間單位晌畅。
Base time constants. 基準時間常數(shù)。
DispatchTime
represents an absolute point in time according to the wall clock with microsecond precision. On Apple platforms, the default clock is based on the result of gettimeofday(2)
.
- DispatchTime表示根據(jù)具有微秒精度的掛鐘的絕對時間點寡痰。 在Apple平臺上抗楔,默認時鐘基于gettimeofday(2)的結(jié)果。
DispatchTimeInterval
represents a number of seconds, millisconds, microseconds, or nanoseconds. You use DispatchTimeInterval
values to specify the interval at which a DispatchSourceTimer
fires or I/O handlers are invoked for a DispatchIO
channel, as well as to increment and decrement DispatchTime
values.
- DispatchTimeInterval表示秒數(shù)拦坠,毫秒连躏,微秒或納秒。 您可以使用DispatchTimeInterval值指定為DispatchIO通道調(diào)用DispatchSourceTimer觸發(fā)或I / O處理程序的時間間隔贞滨,以及遞增和遞減DispatchTime值入热。
DispatchTimeoutResult
indicates whether a dispatch operation finised before a specified time.
- DispatchTimeoutResult指示在指定時間之前是否已完成調(diào)度操作。
A somewhat abstract representation of time.
有點抽象的時間表示晓铆。
-
Managing Dispatch Sources
DispatchSource
provides an interface for monitoring low-level system objects such as Mach ports, Unix descriptors, Unix signals, and VFS nodes for activity and submitting event handlers to dispatch queues for asynchronous processing when such activity occurs.
- DispatchSource提供了一個接口勺良,用于監(jiān)視低級系統(tǒng)對象,如Mach端口骄噪,Unix描述符尚困,Unix信號和VFS節(jié)點,用于活動和提交事件處理程序链蕊,以便在發(fā)生此類活動時調(diào)度隊列以進行異步處理尾组。
protocol DispatchSourceProtocol
Defines a common set of properties and methods that are shared with all dispatch source types.
- 定義與所有調(diào)度源類型共享的一組公共屬性和方法忙芒。
protocol DispatchSourceFileSystemObject
A dispatch source that monitors a file descriptor for events defined by DispatchSource.FileSystemEvent. The handle is a file descriptor (Int32
).
- 一個調(diào)度源,用于監(jiān)視DispatchSource.FileSystemEvent定義的事件的文件描述符讳侨。 句柄是文件描述符(Int32)。
struct DispatchSource.FileSystemEvent
A file system event.
- 文件系統(tǒng)事件奏属。
Managing Dispatch I/O
The dispatch I/O channel API lets you manage file descriptor–based operations. This API supports both stream-based and random-access semantics for accessing the contents of the file descriptor.
- 調(diào)度I / O通道API允許您管理基于文件描述符的操作跨跨。 此API支持基于流和隨機訪問語義,以訪問文件描述符的內(nèi)容囱皿。
DispatchO
provides a channel to perform operations on file descriptor using either stream-based and random-access semantics for accessing the contents of a file descriptor.
- DispatchO提供了一個通道勇婴,使用基于流的和隨機訪問語義對文件描述符執(zhí)行操作,以訪問文件描述符的內(nèi)容嘱腥。
1. dispatch_barrier_async
Submits a barrier block for asynchronous execution and returns immediately.
- 提交用于異步執(zhí)行的屏障塊并立即返回耕渴。
Parameters
queue
The dispatch queue on which to execute the barrier block. The queue is retained by the system until the block has run to completion. This parameter cannot be NULL.
- 要在其上執(zhí)行屏障塊的調(diào)度隊列。 系統(tǒng)保留隊列齿兔,直到塊運行完成橱脸。 此參數(shù)不能為NULL。
block
The barrier block to submit to the target dispatch queue. This block is copied and retained until it finishes executing, at which point it is released. This parameter cannot be NULL.
- 阻止塊提交到目標調(diào)度隊列分苇。 復制并保留此塊添诉,直到它完成執(zhí)行,此時它將被釋放医寿。 此參數(shù)不能為NULL栏赴。
Discussion
Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. When the barrier block reaches the front of a private concurrent queue, it is not executed immediately. Instead, the queue waits until its currently executing blocks finish executing. At that point, the barrier block executes by itself. Any blocks submitted after the barrier block are not executed until the barrier block completes.
- 調(diào)用此函數(shù)后,始終在提交塊后立即返回靖秩,并且永遠不會等待調(diào)用該塊须眷。 當障礙塊到達專用并發(fā)隊列的前面時,它不會立即執(zhí)行沟突。 相反花颗,隊列等待,直到其當前正在執(zhí)行的塊完成執(zhí)行事扭。 此時捎稚,屏障塊自行執(zhí)行。 在屏障塊完成之后求橄,在屏障塊之后提交的任何塊都不會執(zhí)行今野。
The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create
function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_async
function.
- 您指定的隊列應該是您使用dispatch_queue_create函數(shù)自己創(chuàng)建的并發(fā)隊列捧书。 如果傳遞給此函數(shù)的隊列是串行隊列或全局并發(fā)隊列之一韵洋,則此函數(shù)的行為類似于dispatch_async函數(shù)朱盐。
2. dispatch_barrier_sync
Submits a barrier block object for execution and waits until that block completes.
- 提交屏障塊對象以供執(zhí)行蛀恩,并等待該塊完成柴我。
Parameters
queue
The dispatch queue on which to execute the barrier block. This parameter cannot be NULL.
- 要在其上執(zhí)行屏障塊的調(diào)度隊列鸦列。 此參數(shù)不能為NULL发乔。
block
The barrier block to be executed. This parameter cannot be NULL.
- 要執(zhí)行的障礙塊茄螃。 此參數(shù)不能為NULL。
Discussion
Submits a barrier block to a dispatch queue for synchronous execution. Unlike dispatch_barrier_async
, this function does not return until the barrier block has finished. Calling this function and targeting the current queue results in deadlock.
- 將屏障塊提交到調(diào)度隊列以進行同步執(zhí)行拆内。 與dispatch_barrier_async不同旋圆,此功能在屏障塊完成之前不會返回。 調(diào)用此函數(shù)并以當前隊列為目標會導致死鎖麸恍。
When the barrier block reaches the front of a private concurrent queue, it is not executed immediately. Instead, the queue waits until its currently executing blocks finish executing. At that point, the queue executes the barrier block by itself. Any blocks submitted after the barrier block are not executed until the barrier block completes.
- 當障礙塊到達專用并發(fā)隊列的前面時灵巧,它不會立即執(zhí)行。 相反抹沪,隊列等待刻肄,直到其當前正在執(zhí)行的塊完成執(zhí)行。 此時融欧,隊列自己執(zhí)行屏障塊敏弃。 在屏障塊完成之后,在屏障塊之后提交的任何塊都不會執(zhí)行噪馏。
The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create
function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_sync
function.
- 您指定的隊列應該是您使用dispatch_queue_create函數(shù)自己創(chuàng)建的并發(fā)隊列麦到。 如果傳遞給此函數(shù)的隊列是串行隊列或全局并發(fā)隊列之一,則此函數(shù)的行為類似于dispatch_sync函數(shù)逝薪。
Unlike with dispatch_barrier_async
, no retain is performed on the target queue. Because calls to this function are synchronous, it "borrows" the reference of the caller. Moreover, no Block_copy
is performed on the block.
- 與dispatch_barrier_async不同隅要,不對目標隊列執(zhí)行保留。 因為對此函數(shù)的調(diào)用是同步的董济,所以它“借用”調(diào)用者的引用步清。 此外,不對塊執(zhí)行Block_copy虏肾。
As an optimization, this function invokes the barrier block on the current thread when possible.
- 作為優(yōu)化廓啊,此函數(shù)在可能的情況下調(diào)用當前線程上的屏障塊。
dispatch_semaphore_wait
Waits for (decrements) a semaphore.
Parameters
dsema
The semaphore. This parameter cannot be NULL
.
- 信號量封豪。 此參數(shù)不能為NULL谴轮。
timeout
When to timeout (see dispatch_time
). The constants DISPATCH_TIME_NOW
and DISPATCH_TIME_FOREVER
are available as a convenience.
- 何時超時(請參閱dispatch_time)。 為方便起見吹埠,可以使用常量DISPATCH_TIME_NOW和DISPATCH_TIME_FOREVER第步。
Return Value
Returns zero on success, or non-zero if the timeout occurred.
- 成功時返回零,如果超時缘琅,則返回非零粘都。
Discussion
Decrement the counting semaphore. If the resulting value is less than zero, this function waits for a signal to occur before returning.
- 減少計數(shù)信號量。 如果結(jié)果值小于零刷袍,則此函數(shù)在返回之前等待信號發(fā)生翩隧。
dispatch_semaphore_signal
Signals, or increments, a semaphore.
Return Value
If the previous value was less than zero, this function wakes a process currently waiting.
- 如果前一個值小于零,則此函數(shù)喚醒當前正在等待的進程呻纹。
Discussion
Increment the counting semaphore. If the previous value was less than zero, this function wakes a thread currently waiting in dispatch_semaphore_wait
.
- 增加計數(shù)信號量堆生。 如果前一個值小于零专缠,則此函數(shù)喚醒當前在dispatch_semaphore_wait中等待的線程。
dispatch_semaphore_create
Creates new counting semaphore with an initial value.
- 創(chuàng)建具有初始值的新計數(shù)信號量淑仆。
Parameters
value
The starting value for the semaphore. Do not pass a value less than zero.
- 信號量的起始值涝婉。 不要傳遞小于零的值。
Return Value
The newly created semaphore.
Discussion
Passing zero for the value is useful for when two threads need to reconcile the completion of a particular event. Passing a value greater than zero is useful for managing a finite pool of resources, where the pool size is equal to the value.
- 當兩個線程需要協(xié)調(diào)特定事件的完成時糯景,為值傳遞零是有用的嘁圈。 傳遞大于零的值對于管理有限的資源池非常有用,其中池大小等于該值蟀淮。
When your application no longer needs the semaphore, it should call dispatch_release
to release its reference to the semaphore object and ultimately free its memory.
- 當您的應用程序不再需要信號量時,它應調(diào)用dispatch_release以釋放其對信號量對象的引用并最終釋放其內(nèi)存钞澳。
Important
Calls to dispatch_semaphore_signal
must be balanced with calls to wait()
. Attempting to dispose of a semaphore with a count lower than value
causes an EXC_BAD_INSTRUCTION
exception.
- 必須與對wait()的調(diào)用平衡對dispatch_semaphore_signal的調(diào)用怠惶。 嘗試處理計數(shù)低于值的信號量會導致EXC_BAD_INSTRUCTION異常。
dispatch_sync
Submits a block object for execution on a dispatch queue and waits until that block completes.
- 提交塊對象以在調(diào)度隊列上執(zhí)行轧粟,并等待該塊完成策治。
Parameters
queue
The queue on which to submit the block. This parameter cannot be NULL.
- 提交塊的隊列。 此參數(shù)不能為NULL兰吟。
block
The block to be invoked on the target dispatch queue. This parameter cannot be NULL.
- 要在目標調(diào)度隊列上調(diào)用的塊通惫。 此參數(shù)不能為NULL。
Discussion
Submits a block to a dispatch queue for synchronous execution. Unlike dispatch_async
, this function does not return until the block has finished. Calling this function and targeting the current queue results in deadlock.
- 將塊提交到調(diào)度隊列以進行同步執(zhí)行混蔼。 與dispatch_async不同履腋,此功能在塊完成之前不會返回。 調(diào)用此函數(shù)并以當前隊列為目標會導致死鎖惭嚣。
Unlike with dispatch_async
, no retain is performed on the target queue. Because calls to this function are synchronous, it "borrows" the reference of the caller. Moreover, no Block_copy
is performed on the block.
- 與dispatch_async不同晚吞,不對目標隊列執(zhí)行保留槽地。 因為對此函數(shù)的調(diào)用是同步的迁沫,所以它“借用”調(diào)用者的引用集畅。 此外牡整,不對塊執(zhí)行Block_copy逃贝。
As an optimization, this function invokes the block on the current thread when possible.
- 作為優(yōu)化沐扳,此函數(shù)在可能的情況下調(diào)用當前線程上的塊躯嫉。
dispatch_async
Submits a block for asynchronous execution on a dispatch queue and returns immediately.
- 在調(diào)度隊列上提交異步執(zhí)行塊并立即返回祈餐。
Parameters
queue
The queue on which to submit the block. The queue is retained by the system until the block has run to completion. This parameter cannot be NULL.
- 提交塊的隊列。 系統(tǒng)保留隊列屋吨,直到塊運行完成鳍徽。 此參數(shù)不能為NULL阶祭。
block
The block to submit to the target dispatch queue. This function performs Block_copy and Block_release on behalf of callers. This parameter cannot be NULL.
- 要提交到目標調(diào)度隊列的塊。 此函數(shù)代表調(diào)用者執(zhí)行Block_copy和Block_release萨咳。 此參數(shù)不能為NULL培他。
Discussion
This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.
- 此函數(shù)是將塊提交到調(diào)度隊列的基本機制。 調(diào)用此函數(shù)后猛遍,始終在提交塊后立即返回梯醒,并且永遠不會等待調(diào)用該塊茸习。 目標隊列確定是否相對于提交到同一隊列的其他塊串行或同時調(diào)用該塊。 獨立的串行隊列相互同時處理猫胁。