Keyword: GCD dispatch_once single thread safety double-check
Previously in Java, C # and other languages, we implemented lazy loading of the singleton pattern is generally written in the following form (pseudo-code):
Private MyClass () {...}//Privatization construction method
private static MyClass instance; The variable that hosts the object
Pubic static MyClass getinstance () {//Completion of instantiation tasks
if (instance = = NULL) {//First judgment
Lock (obj) {//locking, processing multi-threaded judgment
if (instance = = NULL) {//re-judge, avoid thread switching causing multiple instance objects to appear
Instance = new MyClass (); Complete the final instantiation process
}
}
}
return instance;
}
However, what is often seen in objective-c is this notation:
+ (Instancetype) sharedinstance {
Static ID sharedinstance;
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
Sharedinstance = [self new];
});
return sharedinstance;
}
This does not seem to be a defensive approach to multithreaded programming. In sharedinstance = [self new]; adding log output before and after, it can be found that even in a multithreaded environment, Dispatch_once is only executed once.
In fact, dispatch_once is thread-safe, even if it is called at the same time in multiple threads, and only one block is executed, the call of the other dispatch_once block is blocked until the execution of that block is finished, so throughout the program's running cycle, the Dispatch_ The once block runs only once, and you can determine that the entire dispatch_once block is executed before the next line of code executes, regardless of the current worker thread. If executed, Dispatch_once is quickly skipped, invoked in a similar loop body, and does not have to worry about the additional performance overhead of executing it. If a program contains multiple instances of the same calling class, only one of the instances executes the dispatch_once block [1].
Reference:
[1]. Rob Napier is waiting for the American regiment to move the translation. iOS programming combat. BEIJING, People's post and telecommunications press. 358~359 page
IOS 8:dispatch_once FAQ