Preface
In everyday iOS development, GCD isolates us very well from direct
interaction with threads, or pthread. What we usually deal
with are queues and blocks. After using it for a long time, it is easy
to stop feeling the presence of threads at all.
I had long wanted to find an opportunity to study the lower layers of GCD and appreciate the essence of its design. After some initial research, I found that materials analyzing GCD source code were scarce and scattered, making it difficult to form a complete understanding. One possible reason is that business demand does not strongly require this knowledge; the existing GCD APIs are already enough for most work. Even so, my curiosity about the underlying principles of GCD could not be stopped. On impulse, I decided to dig myself a hole and write a GCD source-code analysis series, describing my own understanding of GCD’s internals.
Choosing the GCD Version
The first step was choosing which version of the GCD source code to analyze. After comparing versions vertically, I found that later versions became larger and larger, with a rapidly increasing number of files and increasingly unfriendly source style. They were filled with a large number of macro-based build options, which made the code mentally expensive to read and not very helpful for understanding the core mechanism. After comparing multiple versions, I finally chose libdispatch-84.5.5.

These are all the project files in that version. It is small, but complete enough; it still contains everything in GCD.
Preparation
Before reading the GCD source code, we need to understand some related basics.
Atomic Operations
Before analyzing the source code, first look at some atomic-operation macros. You do not need to memorize them; just keep an impression and look them up later when needed.
1 |
__sync_lock_test_and_set((p), (n))sets*ptovalueand returns the previous value of*p.__sync_bool_compare_and_swap((p), (o), (n))provides atomic compare-and-swap: if*p == o, writeninto*p. Herepis the address,ois the old value, andnis the new value.__sync_add_and_fetch((p), 1)increments by 1 first, then returns.__sync_sub_and_fetch((p), 1)decrements by 1 first, then returns.__sync_add_and_fetch((p), (v))addsvfirst, then returns.__sync_sub_and_fetch((p), (v))subtractsvfirst, then returns.__sync_fetch_and_or((p), (v))returns first, then performs OR.__sync_fetch_and_and((p), (v))returns first, then performs AND.
__builtin_expect
1 | long __builtin_expect (long EXP, long C) |
Processors generally use a pipeline model, and some contain multiple logical execution units. The system can fetch multiple instructions in advance and process them in parallel. But when it encounters a branch, it may need to fetch instructions again, which is slower than continuing with already-prefetched instructions.
Because programmers are often bad at branch prediction, this built-in
function, __builtin_expect, helps programmers provide
branch-prediction hints and optimize programs. Its first parameter,
EXP, is an integer expression, and the return value of the
built-in function is also EXP. C is a
compile-time constant. Its meaning is: I expect the value of
EXP to equal constant C; the compiler should
optimize based on that expectation.
For example:
1 | if (__builtin_expect(x, 0)) |
Obviously, the expected value of x is 0, meaning
x is very likely to be 0. So the if branch is
less likely. The compiler may compile it like this:
1 | if (!x) |
This way, the CPU is more likely to execute the prefetched compiled
if branch, improving branch-prediction accuracy and thus
instruction execution speed.
fastpath and slowpath
1 |
With __builtin_expect as the foundation, Apple’s
fastpath and slowpath macros are easy to
understand:
fastpathmeans this condition usually happens.slowpathmeans you are confident this condition rarely happens.
DISPATCH_DECL
1 |
This macro appears in many places in the GCD source code. For example:
1 | DISPATCH_DECL(dispatch_queue); |
It expands to:
1 | typedef struct dispatch_queue_s *dispatch_queue_t |
So dispatch_queue_t can be used to define a pointer to a
dispatch_queue_s structure.
Basic Data Structures
dispatch_object_t
1 | typedef union { |
dispatch_object_t is a union, so it can represent every
data type inside that union.
Pay attention to
__attribute__((transparent_union)). This is a
typical transparent union. A transparent union weakens
C’s type-checking mechanism and works somewhat like an implicit cast.
With it, dispatch_object_s behaves like a C++ base class,
making function parameter passing in C much more convenient.
At the lower level, types do not really exist in the same way we usually think about them. A transparent union breaks some of the constraints that types impose on us, allowing data to be viewed from a lower-level perspective. But it also weakens C’s type checking, which can lead to serious errors.
dispatch_object_s
1 | struct dispatch_object_s { |
dispatch_object_s is the base structure of the entire
GCD system, and it is very important. Some fields are briefly explained
in the comments. As the analysis goes deeper, we will gradually
understand why each of these fields exists.
The type of do_vtable is
dispatch_object_vtable_s:
1 | struct dispatch_object_vtable_s { |
This structure contains operation functions for
dispatch_object_s, and it defines short macros for those
operations to make calls more convenient.
dispatch_continuation_s
This structure is mainly used to wrap blocks and functions:
1 | struct dispatch_continuation_s { |
dispatch_continuation_s represents a task. Blocks passed
to dispatch_async are usually wrapped into this data
type.
If dc_vtable is less than 127, then the object is a continuation. Otherwise, the object has a private layout and memory management rules. The first two words must align with normal objects.
dispatch_queue_s
1 |
|
The difference between dispatch_queue_s and
dispatch_object_s is that dispatch_queue_s
adds DISPATCH_QUEUE_HEADER and
dq_label[DISPATCH_QUEUE_MIN_LABEL_SIZE]. This also tells us
that queue names should be shorter than 64 characters.
dispatch_group_s
1 | DISPATCH_DECL(dispatch_group); |
dispatch_group_t is equivalent to
dispatch_group_s *. But what is
dispatch_group_s really? I could not find its structure
definition anywhere in the source. So I had to take another path.
While reading the source, I found a clue in the definition of
dispatch_group_create in semaphore.c:
1 | dispatch_group_t |
The result is quite surprising: dispatch_group_t is
essentially a semaphore whose value is LONG_MAX.
dispatch_source_s
1 | struct dispatch_source_s { |
dispatch_semaphore_s
1 | struct dispatch_semaphore_s { |
UML Diagram
libdispatch Initialization
1 | void libdispatch_init(void) |
pthread_key_t
In a multithreaded environment, data space is shared, so global variables are also shared by all threads. But sometimes an application needs thread-private global variables: values that are valid only inside a certain thread but can still be accessed across multiple functions. For example, each thread may need to maintain its own linked list while using the same functions to operate on it.
The simplest way is to use thread-specific data structures with the same name but different variable addresses. This kind of data structure is called Thread-Specific Data, or TSD.
GCD defines four keys:
1 | static const unsigned long dispatch_queue_key = __PTK_LIBDISPATCH_KEY0; |
pthread_key_create
_dispatch_thread_key_init_np calls
pthread_key_create:
1 | int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)) |
This function allocates an entry from the TSD pool and assigns its
value to key for later access. If
destr_function is not empty, when the thread exits through
pthread_exit(), destr_function() is called
with the data associated with key, allowing allocated
buffers to be released.
No matter which thread calls pthread_key_create(), the
created key is accessible to all threads. But each thread can fill that
key with a different value according to its own needs. These values are
thread-specific and maintained independently for each thread. This is
equivalent to providing a global variable with the same name but
different values per thread.
pthread_setspecific and pthread_getspecific
Here, the main thread sets its TSD to the address of
_dispatch_main_q:
1 | _dispatch_thread_setspecific(dispatch_queue_key, &_dispatch_main_q); |
Summary
The basic data structures covered in this article are mainly here to make them familiar. Explaining data structures only for the sake of data structures is not enough to make everything clear. In the following GCD source-code analysis articles, these pieces will be clarified step by step.