Common GCD methods, gcd
1. Delayed operations
2. One-time code
3. Queue Group
/*** Delayed execution of dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (2.0 * NSEC_PER_SEC), dispatch_get_main_queue (), ^ {// execute the code here asynchronously after 2 seconds ...}); delayed execution: there is no need to write a method, and it also transmits a queue. We can specify and arrange its thread. If the queue is a main queue column, it is executed in the main thread. If the queue is a concurrent queue, a new thread is enabled and executed in the Child thread. */-(Void) test1 {NSLog (@ "Print current thread --- % @", [NSThread currentThread]); // delayed execution, the second method // you can arrange the thread (1), the main queue column queue = queue (); dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (5.0 * NSEC_PER_SEC), queue, ^ {NSLog (@ "main queue column -- delayed execution ------ % @", [NSThread currentThread]) ;}); // you can schedule the thread (2 ), concurrent queue // 1. obtain the global concurrency queue dispatch_queue_t queue1 = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2. computing task execution time dispatch_time_t when = dispatch_time (DISPATCH_TIME_NOW, (int64_t) (5.0 * NSEC_PER_SEC); // 3. run the dispatch_after (when, queue1, ^ {NSLog (@ "concurrent queue-delayed execution ------ % @", [NSThread currentThread]);}
/*** 2. using the dispatch_once one-time code using the dispatch_once function ensures that a piece of code is only executed once during the program running. static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// code that is executed only once (thread-safe by default)}); the entire program runs only once. */-(Void) test2 {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {NSLog (@ "this line of code is executed only once ");});}
/*** Queue group */-(void) test3 {dispatch_group_t group = dispatch_group_create (); dispatch_group_async (group, dispatch_get_global_queue (queue, 0 ), ^ {// execute 1 time-consuming Asynchronous Operation}); dispatch_group_async (group, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {// execute 1 time-consuming Asynchronous Operation }); dispatch_group_notify (group, dispatch_get_main_queue (), ^ {// after all the preceding asynchronous operations are completed, return to the main thread... (result processing )});}