iOS single case

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.