Today, when we look at multi-thread synchronization, I suddenly think of a single-instance synchronization problem. Since the advent of dispatch_once, we have created a single example that is very simple and safe:
1 Static dispatch_once_t pred; 2 Static Singleobject *sharedobject = nil; 3 4 dispatch_once (&pred, ^{5 class] alloc] init]; 6 }); 7 return Sharedobject;
View Code
Apple's simple interface has slowly let us forget the synchronization problem when creating a singleton.
Common ways to create a single case:
1 Static Singleobject *obj = nil; 2 3 @synchronized (self) {4 if (obj = nil) {5 obj = [[Singleobject alloc] init]; 6 }7}8 9return obj;
View Code
This is fine, but when multiple threads are invoked at the same time, it is inefficient to use the famous double check method to improve efficiency:
1 Static Singleobject *obj = nil; 2 3 if (obj = nil) {4 @synchronized (self) {5 if (obj = = Nil {6 obj = [[Singleobject alloc] init]; 7 }8 }9 }
View Code
If there is no first if (obj = = nil), each call to this method will use a lock operation to implement thread synchronization, which is very performance-intensive.
With the if (obj = = nil), the second call to this method will not enter the lock module in the code, only obj = nil, will enter the lock code once,
This can improve the performance of the lock due to the problem.
iOS single case