在 GCD 出現之前, thread-safe 的單例通常得靠 @synchronized 或 double-checked locking 來實作,寫起來囉嗦又容易出錯。dispatch_once 把這件事變成了一行。
void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block);
傳入的 block 無論被提交多少次,只會執行一次,而且是執行緒安全的。兩個參數的含義:
另外要理解一件事:dispatch_once 的 block 預設在被呼叫的執行緒上執行,也就是呼叫它的那條執行緒。
- (void)viewDidLoad {
[super viewDidLoad];
static dispatch_once_t onceToken;
void (^executedOnlyOnce)(void) = ^(void) {
static NSUInteger numberOfEntries = 0;
numberOfEntries++;
NSLog(@"Executed %lu time(s) %@",
(unsigned long)numberOfEntries, [NSThread currentThread]);
};
dispatch_once(&onceToken, ^(void) {
dispatch_async(concurrentQueue, executedOnlyOnce);
});
dispatch_once(&onceToken, ^(void) {
dispatch_async(concurrentQueue, executedOnlyOnce);
});
static dispatch_once_t testToken;
dispatch_once(&testToken, ^(void) {
NSLog(@"####: Current thread = %@", [NSThread currentThread]);
});
}
輸出結果類似:
####: Current thread = <NSThread: 0x8a1e7c0>{name = (null), num = 1}
Executed 1 time(s) <NSThread: 0x8a794c0>{name = (null), num = 2}
可以觀察到三件事:
+ (MyClass *)sharedInstance {
static MyClass *_sharedMyClass = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
_sharedMyClass = [[MyClass alloc] initWithSomething:something];
});
return _sharedMyClass;
}
這個寫法之所以成為標準範式,是因為它同時滿足了三個條件:執行緒安全、只在第一次呼叫時才建立(lazy initialization)、而且沒有 lock 帶來的效能負擔。
[[MyClass alloc] init] 建立第二個實例,dispatch_once 只保證 sharedInstance 這條路徑的唯一性。若要求絕對唯一,需要覆寫 allocWithZone:、init 與 copy 等方法,或把初始化方法標記為不該被外部呼叫。dispatch_once 的本質是「某段程式碼只跑一次」,所以它也常被用來做單例以外的事:
需要注意的是,unit test 若希望每個測試都重跑一次初始化,就不能用 dispatch_once,因為它的「只跑一次」是以整個行程生命週期為單位,而非以某個物件或某次執行為單位。