GCD Source Analysis 2 - dispatch_once

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
2
3
4
5
6
7
8
+ (instancetype)sharedInstance {
static XXObject *_instance;
static dispatch_once_t _predicate;
dispatch_once(&_predicate, ^{
_instance = [[XXObject alloc] init];
});
return _instance;
}

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
2
3
4
void dispatch_once(dispatch_once_t *val, void (^block)(void)){
struct Block_basic *bb = (void *)block;
dispatch_once_f(val, block, (void *)bb->Block_invoke);
}

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_basic is likely a structure whose pointer can point to a void (^block)(void) block.
  • Block_invoke literally means invoking a block. The following code can help with that intuition:
1
2
3
4
5
6
void _dispatch_call_block_and_release(void *block)
{
void (^b)(void) = block;
b();
Block_release(b);
}

Now analyze the core function, dispatch_once_f:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void dispatch_once_f(dispatch_once_t *val, void *ctxt, void (*func)(void *)){

volatile long *vval = val;
if (dispatch_atomic_cmpxchg(val, 0l, 1l)) {
func(ctxt); // the block is really executed here
dispatch_atomic_barrier();
*val = ~0l;
}
else
{
do
{
_dispatch_hardware_pause();
} while (*vval != ~0l);
dispatch_atomic_barrier();
}
}
    1. As mentioned in the opening article, dispatch_atomic_cmpxchg is 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: if p == o, set p to n and return true; otherwise, do nothing and return false.
    1. In a multithreaded environment, if thread A enters dispatch_once_f for the first time and *val == 0, it atomically changes the value to 1, executes the block passed into dispatch_once_f, calls dispatch_atomic_barrier, and finally changes *val to ~0.
    1. dispatch_atomic_barrier is 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_barrier guarantees that *val is modified only after the block finishes executing.
    1. While thread A is executing the block, if other threads also enter dispatch_once_f, the atomic check in the if branch must return false, so they enter the else branch and run the do-while loop. Inside the loop, _dispatch_hardware_pause is called. This helps improve performance and reduce CPU power usage. pause is similar to nop: it delays while spinning. The loop exits only after the first thread has finished executing the block and changed *val to ~0, followed by another dispatch_atomic_barrier. This means other threads cannot execute the block, which guarantees the uniqueness of the block execution in dispatch_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:
  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.
  2. Some function inside block() calls dispatch_sync_safe, synchronously executing code on thread T2.
  3. A function currently running on T2 needs singleton A, so it calls dispatch_once again.
  4. Now T1 is waiting for the block to finish. The block is waiting for T2 to finish. T2 is waiting for T1’s dispatch_once to complete. They wait on each other, causing a deadlock.
  • Deadlock pattern 2:
  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 it.
  2. The block may call flow B, flow B calls flow C, and flow C may call singleton A again, triggering dispatch_once again.
  3. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#ifdef __has_feature(objc_arc) 

#define singleton_h +(instancetype)sharedInstance;

#define singleton_m static id _instanceType = nil;\
+(instancetype)sharedInstance\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [[self alloc]init];\
});\
return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [super allocWithZone:zone];\
});\
return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instanceType;\
}

#else

#define singleton_h +(instancetype)sharedInstance;

#define singleton_m static id _instanceType = nil;\
+(instancetype)sharedInstance\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [[self alloc]init];\
});\
return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [super allocWithZone:zone];\
});\
return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instanceType;\
}\
-(oneway void)release\
{\
\
}\
-(instancetype)retain\
{\
return _instanceType;\
}\
-(instancetype)autorelease\
{\
return _instanceType;\
}\
- (NSUInteger)retainCount\
{\
return 1;\
}

#endif

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.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:GCD Source Analysis 2 - dispatch_once

Author:lingyun

Published:2018-02-01 21:59

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/02/01/gcd-source-analysis-2-dispatch-once/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.