Grand Central Dispatch
   HOME

TheInfoList



OR:

Grand Central Dispatch (GCD or libdispatch), is a technology developed by Apple Inc. to optimize application support for systems with
multi-core A multi-core processor is a microprocessor on a single integrated circuit with two or more separate processing units, called cores, each of which reads and executes program instructions. The instructions are ordinary CPU instructions (such ...
processors and other
symmetric multiprocessing Symmetric multiprocessing or shared-memory multiprocessing (SMP) involves a multiprocessor computer hardware and software architecture where two or more identical processors are connected to a single, shared main memory, have full access to all ...
systems. It is an implementation of
task parallelism Task parallelism (also known as function parallelism and control parallelism) is a form of parallelization of computer code across multiple processors in parallel computing environments. Task parallelism focuses on distributing tasks—concurrent ...
based on the
thread pool pattern In computer programming, a thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for ...
. The fundamental idea is to move the management of the thread pool out of the hands of the developer, and closer to the operating system. The developer injects "work packages" into the pool oblivious of the pool's architecture. This model improves simplicity, portability and performance. GCD was first released with Mac OS X 10.6, and is also available with iOS 4 and above. The name "Grand Central Dispatch" is a reference to
Grand Central Terminal Grand Central Terminal (GCT; also referred to as Grand Central Station or simply as Grand Central) is a commuter rail terminal located at 42nd Street and Park Avenue in Midtown Manhattan, New York City. Grand Central is the southern terminus ...
. The source code for the library that provides the implementation of GCD's services, ''libdispatch'', was released by Apple under the Apache License on September 10, 2009. It has been ported to
FreeBSD FreeBSD is a free and open-source Unix-like operating system descended from the Berkeley Software Distribution (BSD), which was based on Research Unix. The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the most popular ...
8.1+,
MidnightBSD MidnightBSD is a free Unix, desktop-oriented operating system originally forked from FreeBSD 6.1, and periodically updated with code and drivers from later FreeBSD releases. Its default desktop environment, Xfce, is a lightweight user friendly ...
0.3+, Linux, and Solaris. Attempts in 2011 to make libdispatch work on Windows were not merged into upstream. Apple has its own port of libdispatch.dll for Windows shipped with Safari and iTunes, but no SDK is provided. Since around 2017, the original libdispatch repository hosted by Nick Hutchinson was deprecated in favor of a version that is part of the
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
core library created in June 2016. The new version supports more platforms, notably including Windows.


Design

GCD works by allowing specific tasks in a program that can be run in parallel to be queued up for execution and, depending on availability of processing resources,
scheduling A schedule or a timetable, as a basic time-management tool, consists of a list of times at which possible tasks, events, or actions are intended to take place, or of a sequence of events in the chronological order in which such things are ...
them to execute on any of the available processor cores (referred to as "routing" by Apple). A task can be expressed either as a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
or as a "
block Block or blocked may refer to: Arts, entertainment and media Broadcasting * Block programming, the result of a programming strategy in broadcasting * W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
." Blocks are an extension to the syntax of C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, and
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
programming languages that encapsulate code and data into a single object in a way similar to a closure. GCD can still be used in environments where blocks are not available. Grand Central Dispatch still uses threads at the low level but abstracts them away from the programmer, who will not need to be concerned with as many details. Tasks in GCD are lightweight to create and queue; Apple states that 15 instructions are required to queue up a work unit in GCD, while creating a traditional thread could easily require several hundred instructions. A task in Grand Central Dispatch can be used either to create a work item that is placed in a queue or assign it to an event source. If a task is assigned to an event source, then a work unit is made from the block or function when the event triggers, and the work unit is placed in an appropriate queue. This is described by Apple as more efficient than creating a thread whose sole purpose is to wait on a single event triggering.


Features

The dispatch framework declares several data types and functions to create and manipulate them: * ''Dispatch Queues'' are objects that maintain a queue of ''tasks'', either anonymous code blocks or functions, and execute these tasks in their turn. The library automatically creates several queues with different priority levels that execute several tasks concurrently, selecting the optimal number of tasks to run based on the operating environment. A client to the library may also create any number of serial queues, which execute tasks in the order they are submitted, one at a time. Because a serial queue can only run one task at a time, each task submitted to the queue is critical with regard to the other tasks on the queue, and thus a serial queue can be used instead of a
lock Lock(s) may refer to: Common meanings *Lock and key, a mechanical device used to secure items of importance *Lock (water navigation), a device for boats to transit between different levels of water, as in a canal Arts and entertainment * ''Lock ...
on a contended resource. * ''Dispatch Sources'' are objects that allow the client to register blocks or functions to execute asynchronously upon system events, such as a
socket Socket may refer to: Mechanics * Socket wrench, a type of wrench that uses separate, removable sockets to fit different sizes of nuts and bolts * Socket head screw, a screw (or bolt) with a cylindrical head containing a socket into which the hexag ...
or
file descriptor In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically ha ...
being ready for reading or writing, or a POSIX
signal In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The '' IEEE Transactions on Signal Processing' ...
. * ''Dispatch Groups'' are objects that allow several tasks to be grouped for later joining. Tasks can be added to a queue as a member of a group, and then the client can use the group object to wait until all of the tasks in that group have completed. * ''Dispatch Semaphores'' are objects that allow a client to permit only a certain number of tasks to execute concurrently. Libdispatch comes with its own object model, ''OS Object'', that is partially compatible with the Objective-C model. As a result, its objects can be bridged ''toll-free'' to ObjC objects.


Examples

Two examples that demonstrate the use of Grand Central Dispatch can be found in John Siracusa's ''
Ars Technica ''Ars Technica'' is a website covering news and opinions in technology, science, politics, and society, created by Ken Fisher and Jon Stokes in 1998. It publishes news, reviews, and guides on issues such as computer hardware and software, sc ...
'' Snow Leopard review.Mac OS X 10.6 Snow Leopard: the Ars Technica review
(accessed September 2, 2009)
Initially, a document-based application has a method called analyzeDocument which may do something like count the number of words and paragraphs in the document. Normally, this would be a quick process, and may be executed in the main thread without the user noticing a delay between pressing a button and the results showing. - (IBAction)analyzeDocument:(NSButton *)sender If the document is large and analysis takes a long time to execute then the main thread will wait for the function to finish. If it takes long enough, the user will notice, and the application may even " beachball". The solution can be seen here: - (IBAction)analyzeDocument:(NSButton *)sender Here, the call to yDoc analyze/code> is placed inside a
Block Block or blocked may refer to: Arts, entertainment and media Broadcasting * Block programming, the result of a programming strategy in broadcasting * W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
, which is then placed on one of the global concurrent queues. After it has finished running yDoc analyze/code>, a new block is placed on the main queue (on which the main thread of the application runs), which updates the
GUI The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
(This is necessary because the GUI can only be updated by the main thread). By making these two small changes, the developer has avoided a potential stall of the application as seen by the user, and allowed their application to make better use of hardware resources. The second example is that of parallelising a for loop: for (i = 0; i < count; i++) total = summarize(results, count); This code runs the do_work function count times, assigning the ith result to the ith element in the array results, and then calls summarize on array once the loop has ended. Unfortunately the work is computed sequentially, where it may not need to be. Assuming that do_work doesn't rely on the results of any of the other calls made to it, there is no reason why these calls cannot be made concurrently. This is how this would be done in GCD: dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i)); total = summarize(results, count); Here, dispatch_apply runs the block passed to it, count times, placing each invocation on a global queue, and passing each block invocation a different number from 0 to count-1. This will allow the OS to spread out the work as it sees fit, choosing the optimal number of threads to run on for the current hardware and system load. dispatch_apply does not return until all the blocks it places on the given queue have completed execution, so that it can be guaranteed that all the work inside the original loop has completed before calling summarize. Programmers can create their own serial queues for tasks which they know must run serially but which may be executed on a separate thread. A new queue would be created like so: dispatch_queue_t exampleQueue; exampleQueue = dispatch_queue_create( "com.example.unique.identifier", NULL ); // exampleQueue may be used here. dispatch_release( exampleQueue ); Care must be taken to avoid a dispatched block on a queue synchronously placing another block on the same queue as this is guaranteed to deadlock. Such code might do the following: dispatch_queue_t exampleQueue = dispatch_queue_create( "com.example.unique.identifier", NULL ); dispatch_sync( exampleQueue, ^); dispatch_release( exampleQueue );


Applications

GCD is used throughout macOS (beginning with 10.6 Snow Leopard), and Apple has encouraged its adoption by macOS application developers.
FreeBSD FreeBSD is a free and open-source Unix-like operating system descended from the Berkeley Software Distribution (BSD), which was based on Research Unix. The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the most popular ...
developer Robert Watson announced the first adaptation of a major open source application, the
Apache HTTP Server The Apache HTTP Server ( ) is a free and open-source cross-platform web server software, released under the terms of Apache License 2.0. Apache is developed and maintained by an open community of developers under the auspices of the Apache S ...
, to use GCD via the Apache GCD MPM (Multi-Processing Module) on May 11, 2010, in order to illustrate the programming model and how to integrate GCD into existing, large-scale multi-threaded, applications. His announcement observed that the GCD MPM had one third to half the number of lines as other threaded MPMs.libdispatch-dev GCD MPM for Apache
(accessed May 14, 2010)
apache-libdispatch
(accessed May 14, 2010)


Internals

GCD is implemented by libdispatch, with support from pthreads non-POSIX extensions developed by Apple. Apple has changed the interface since its inception (in OS X 10.5) through the official launch of GCD (10.6), Mountain Lion (10.8) and Mavericks (10.9). The latest changes involve making the code supporting pthreads, both in user mode and kernel, private (with kernel pthread support reduced to shims only, and the actual ''workqueue'' implementation moved to a separate kernel extension). On other systems, libdispatch implements its own ''workqueue'' using the system's own event facilities (epoll, kevent, or Windows NT). On macOS, kevent is used with the kernel workqueue.


See also

*
Task Parallel Library Parallel Extensions was the development name for a managed concurrency library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) ...
*
Java Concurrency The Java programming language and the Java virtual machine (JVM) have been designed to support concurrent programming, and all execution takes place in the context of threads. Objects and resources can be accessed by many separate threads; each t ...
*
OpenMP OpenMP (Open Multi-Processing) is an application programming interface (API) that supports multi-platform shared-memory multiprocessing programming in C, C++, and Fortran, on many platforms, instruction-set architectures and operating syst ...
*
Threading Building Blocks oneAPI Threading Building Blocks (oneTBB; formerly Threading Building Blocks or TBB), is a C++ template library developed by Intel for parallel programming on multi-core processors. Using TBB, a computation is broken down into tasks that ca ...
(TBB)


References


External links


GCD project on GitHub

GCD Reference from the Mac Developer Library


{{Mac OS X MacOS Parallel computing