Preface
Among the GCD source-code analysis articles,
dispatch_once is one of the smallest APIs, but it is also
one of the most commonly used. Its implementation is a good entry point
for understanding libdispatch’s low-level synchronization style.
dispatch_once Analysis
In iOS development, we often use dispatch_once to define
a singleton and guarantee object uniqueness. But have we really looked
at how dispatch_once guarantees that only one object is
created in a multithreaded environment? For example, we often create a
singleton with code like this:
1 | + (instancetype)sharedInstance { |
This code involves two key terms: dispatch_once_t and
dispatch_once. Let’s analyze them one by one.
dispatch_once_t
In once.h, it is defined as:
1 | typedef long dispatch_once_t; |
So dispatch_once_t is actually a long integer. Quite
unexpected.
dispatch_once
1 | void dispatch_once(dispatch_once_t *val, void (^block)(void)){ |
Inside dispatch_once, a Block_basic pointer
is created and made to point to the block. Its Block_invoke
function pointer is then passed to dispatch_once_f.
You may wonder what Block_basic and
Block_invoke are. Unfortunately, they cannot be found
directly in the source code, but we can infer:
Block_basicis likely a structure whose pointer can point to avoid (^block)(void)block.Block_invokeliterally means invoking a block. The following code can help with that intuition:
1 | void _dispatch_call_block_and_release(void *block) |
Now analyze the core function, dispatch_once_f:
1 | void dispatch_once_f(dispatch_once_t *val, void *ctxt, void (*func)(void *)){ |
- As mentioned in the opening article,
dispatch_atomic_cmpxchgis a macro whose prototype is__sync_bool_compare_and_swap((p), (o), (n)). It is a lock-free atomic operation based on CAS. The principle is: ifp == o, setptonand return true; otherwise, do nothing and return false.
- In a multithreaded environment, if thread A enters
dispatch_once_ffor the first time and*val == 0, it atomically changes the value to 1, executes the block passed intodispatch_once_f, callsdispatch_atomic_barrier, and finally changes*valto~0.
dispatch_atomic_barrieris a memory barrier. From the processor’s perspective, a memory barrier serializes read and write operations. From the software perspective, it solves sequential consistency problems. The compiler may reorder instructions, and the processor may execute instructions out of order. Inserting a memory barrier is equivalent to telling the compiler that instructions before and after the barrier cannot be reordered, and telling the processor that instructions after the barrier can only begin after instructions before it are complete. Therefore,dispatch_atomic_barrierguarantees that*valis modified only after the block finishes executing.
- While thread A is executing the block, if other threads also enter
dispatch_once_f, the atomic check in theifbranch must return false, so they enter theelsebranch and run thedo-whileloop. Inside the loop,_dispatch_hardware_pauseis called. This helps improve performance and reduce CPU power usage.pauseis similar tonop: it delays while spinning. The loop exits only after the first thread has finished executing the block and changed*valto~0, followed by anotherdispatch_atomic_barrier. This means other threads cannot execute the block, which guarantees the uniqueness of the block execution indispatch_once_f, and therefore the singleton is unique.
dispatch_once Deadlocks
After all that, does it mean singletons written with
dispatch_once are completely worry-free?
Not really. Improper use of dispatch_once can cause
deadlocks.
- Deadlock pattern 1:
- Thread T1 calls singleton A. This is the first call in the
application’s lifetime, so
dispatch_once(&token, block())is used to initialize the singleton. - Some function inside
block()callsdispatch_sync_safe, synchronously executing code on thread T2. - A function currently running on T2 needs singleton A, so it calls
dispatch_onceagain. - Now T1 is waiting for the block to finish. The block is waiting for
T2 to finish. T2 is waiting for T1’s
dispatch_onceto complete. They wait on each other, causing a deadlock.
- Deadlock pattern 2:
- Thread T1 calls singleton A. This is the first call in the
application’s lifetime, so
dispatch_once(&token, block())is used to initialize it. - The block may call flow B, flow B calls flow C, and flow C may call
singleton A again, triggering
dispatch_onceagain. - This again creates mutual waiting.
So when writing singletons, keep these points in mind:
- Keep initialization as simple as possible.
- Try to make initialization self-contained and reduce dependencies on other modules or classes.
- Think carefully about whether a singleton is really needed. Do not create singletons casually, because once initialized they keep occupying resources and cannot be released, causing waste.
A Convenient Singleton Macro with dispatch_once
1 |
Then add singleton_h to the .h file of the
singleton you want to implement, and add singleton_m to the
.m file.
Summary
The analysis of dispatch_once is the simplest one. That
also means the later articles in this series will gradually become more
complex. The storm is coming.