Ios multi-thread operations-GCD latency operations and one-time code

Source: Internet
Author: User

Ios multi-thread operations-GCD latency operations and one-time code
You can use the GCD function to perform latency operations. This function is

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{    });


Now let's break down the parameters. Dispatch_time (DISPATCH_TIME_NOW, (int64_t) (delayInSeconds * NSEC_PER_SEC )):The NSEC_PER_SEC header file is defined as follows:
# Define NSEC_PER_SEC 000000000ull/* nanoseconds per second */This parameter indicates the number of nanoseconds that have elapsed since now dispatch_get_main_queue (): indicates the main queue column ^ {}: indicates a block task. We can test whether the scheduling tasks in the main queue are executed asynchronously or synchronously after several nanoseconds. The Code is as follows:
// How many nanosecond dispatch_time_t when = dispatch_time (DISPATCH_TIME_NOW, (int64_t) (1.0 * NSEC_PER_SEC) after the when time starts from now; void (^ task )() =={ // code NSLog (@ "% @", [NSThread currentThread]) for delayed operation execution, the scheduling task in the main queue executes dispatch_after (when, dispatch_get_main_queue (), task) asynchronously. // the first execution is asynchronous, and the second execution is synchronous NSLog (@ "come here ");

The execution result is as follows:
It can be seen that the scheduling task in the main queue column is asynchronously executed, and then the execution queue is changed to a global queue and a serial queue. The results are exactly the same. From this, we can see that the function is executing an asynchronous operation.
There is a function in GCD to ensure that a piece of code is only executed once during the program running! This function is as follows:
static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{           })

Dispatch_once_t is defined in the header file as follows:
Typedef long dispatch_once_t; it can be seen that this type is a long type. When onceToken is equal to 0, block code is executed. Dispatch_once is thread-safe. As long as thread security is involved, locks are involved. dispatch_once also has a lock internally, which has a higher performance than mutex locks! With this function, we can write a singleton mode. Singleton mode ensures that the program is running. A class has only one instance and the instance is easy for external access, so as to conveniently control the number of instances, it also saves system resources and can be implemented in singleton mode when an application needs to share a resource. The Singleton mode is divided into ARC and MRC. We can use macros to determine whether the ARC environment is used.

 

#if __has_feature(objc_arc)// ARC#else// MRC#endif

 

Simple Singleton mode in the ARC environment:
@ Implementation SoundTools // defines a static member and stores a unique static id instance. // ensure that the object is allocated only once, dispatch_once ensures that the allocation and initialization of a single instance is thread-Safe + (instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {instance = [super allocWithZone: zone] ;}); return instance ;}// ensure that the object is initialized only once + (instancetype) sharedSoundTools {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {instance = [[self alloc] init] ;}); return instance ;}- (id) copyWithZone :( NSZone *) zone {return instance ;} @ end test code:-(void) viewDidLoad {[super viewDidLoad]; SoundTools * s1 = [SoundTools sharedSoundTools]; NSLog (@ "% p", s1 );} -(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {SoundTools * s2 = [SoundTools sharedSoundTools]; NSLog (@ "% p", s2 );}


The addresses printed by the two methods are exactly the same!
The following code is available in the MRC environment:
// Define a static member and save the unique static id instance of the instance; // ensure that the object is allocated only once, dispatch_once ensures that the allocation and initialization of a single instance is thread-Safe + (instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {instance = [super allocWithZone: zone] ;}); return instance ;}// ensure that the object is initialized only once + (instancetype) sharedSoundTools {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {instance = [self all Oc] init];}); return instance;}-(id) copyWithZone :( NSZone *) zone {return instance ;} # pragma mark-MRC memory management method/** because the objects in a single instance are stored in the static zone, you need to override the memory management method to cancel the default reference count operation! * /// Reference count-1-(oneway void) release {// does nothing by default, similar to highlight} // default reference count + 1, at the same time, an object-(instancetype) retain {return instance;} // by default, the automatic release tag is added to delay release! -(Instancetype) autorelease {return instance;} // returns the number of objects that reference the current object-(NSUInteger) retainCount {// Source: limits. h will adjust the integer length according to the CPU architecture. return ULONG_MAX ;}


Related Article

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.