Multi-thread (GCD) for iOS development practices)

Source: Internet
Author: User

Multi-thread (GCD) for iOS development practices)
What is GCD: 1. GCD is a multi-core programming solution developed by Apple. It is easier to use than other multi-threaded technical solutions.
2. Pure C language: GCD provides many powerful functions. 1. GCD is a solution developed by Apple for multi-core parallel computing.
2. GCD will automatically use more CPU cores (such as dual-core and quad-core)
3. GCD automatically manages the thread lifecycle (creating threads, scheduling tasks, and destroying threads)
4. the programmer only needs to tell GCD what task to execute and does not need to write any thread to manage code queues and tasks:

There are two core concepts in GCD

Task: What operations are performed, and block is used to encapsulate the task.

Queue: used to store tasks.

After a task is added to the queue, GCD automatically retrieves the tasks in the queue and puts them in the corresponding thread for execution.

Task retrieval follows the FIFO principle of the queue: first-in-first-out, and then-out.

Queue type

Concurrent queue: Allows concurrent (concurrent) Execution of multiple tasks (enabling multiple threads to execute tasks at the same time). The concurrent function is only valid under the asynchronous (dispatch_async) function.

1. Obtain a global concurrent queue

// Queue priority: queue priority // unsigned long flags: this parameter is useless currently. Use 0 to dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
Priority of global concurrent queues
# Define DISPATCH_QUEUE_PRIORITY_HIGH 2 // high
# Define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // default (medium)
# Define DISPATCH_QUEUE_PRIORITY_LOW (-2) // low
# Define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN // background

Serial queue: Let the task be executed one by one (after a task is executed, execute the next task ).

1. Use the dispatch_queue_create function to create a serial queue.

// Const char * label: queue name // dispatch_queue_attr_t attr: queue attribute. Generally, use NULL to dispatch_queue_t queue = dispatch_queue_create ("cn. XXX", NULL );
Dispatch_release (queue); // non-ARC queue needs to be released manually

2. Use the main queue column (the queue associated with the main thread). The main queue column is a special serial queue that comes with GCD.
All tasks in the main queue are executed in the main thread.
Use dispatch_get_main_queue () to obtain the main queue Column

dispatch_queue_t queue = dispatch_get_main_queue();

Execute the task:

1. Execute the task in synchronous Mode

dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);
2. execute tasks asynchronously.
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);

Differences between synchronous and asynchronous:

1. Synchronization: Only tasks can be executed in the current thread, and new threads cannot be enabled. Dispatch_sync

2. asynchronous: You can execute tasks in new threads and enable new threads. Dispatch_async

Combined Analysis of queue and task execution methods:

Ps Special Note: using the sync function to add tasks to the current serial queue will get stuck in the current serial queue

/* ** Asynchronous global concurrency * async concurrent Queue (most commonly used) * creates a thread. Generally, multiple * concurrent executions **/-(void) are enabled at the same time) asyncGlobalQueue {// obtain the global concurrency queue // queue priority: queue priority // unsigned long flags: this parameter is useless for the moment. Use 0 to dispatch_queue_t queue = dispatch_get_global_queue (bytes, 0 ); // Add the task to the global queue and asynchronously execute dispatch_async (queue, ^ {NSLog (@ "------ download image 1 ---- % @", [NSThread currentThread]);}); dispatch_async (queue, ^ {NSLog (@ "----- download Image 2 ----- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "---- download Image 3 ------ % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "----- download Image 4 ---- % @", [NSThread currentThread]) ;}/ *** serial Queue (sometimes used) * A thread is created. Generally, only one * serial execution is enabled (the next task is executed after a task is executed). **/-(void) asyncSerialQueue {// create a serial queue // const char * label: queue name // dispatch_queue_attr_t attr: queue attribute. Generally, use NULL to dispatch_queue_t queue = dispatch_queue_create ("cn. XXX ", NULL); // Add the task to the serial queue and asynchronously execute dispatch_async (queue, ^ {NSLog (@" -------- download image 1 --------- % @", [NSThread currentThread]);}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 2 --------- % @", [NSThread currentThread]);}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 3 --------- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 4 --------- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "-------- download image 5 --------- % @", [NSThread currentThread]) ;}/ *** async -- main queue column (frequently used) **/-(void) asyncMainQueue {// The main queue column (tasks added to the main queue column are automatically placed in the main thread for execution) dispatch_queue_t queue = dispatch_get_main_queue (); // Add the task to the main queue and asynchronously execute dispatch_async (queue, ^ {NSLog (@ "-------- download image 1 --------- % @", [NSThread currentThread]);}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 2 --------- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 3 --------- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "-------- download Image 4 --------- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {NSLog (@ "-------- download image 5 --------- % @", [NSThread currentThread]) ;}/ *** sync -- main queue column (unavailable, stuck) **/-(void) syncMainQueue {// The main queue column (tasks added to the main queue column will be automatically put into the thread for execution) dispatch_queue_t queue = dispatch_get_main_queue (); // Add the task to the main queue and execute dispatch_sync (queue, ^ {NSLog (@ "-------- download image 1 --------- % @", [NSThread currentThread]);}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 2 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 3 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 4 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download image 5 --------- % @", [NSThread currentThread]) ;});} /*** sync -- Concurrent queue * does not create a thread * for serial execution (the next task is executed after a task is executed) * concurrent queues lose the concurrency function **/-(void) syncGlobalQueue {// obtain the global concurrent queue dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ); // Add the task to the global concurrent queue and run dispatch_sync (queue, ^ {NSLog (@ "-------- download image 1 --------- % @", [NSThread currentThread]);}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 2 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 3 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 4 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download image 5 --------- % @", [NSThread currentThread]) ;});} /*** sync -- serial queue * does not create thread * serial execution (the next task is executed after a task is executed) **/-(void) syncSerialQueue {// create a serial queue dispatch_queue_t queue = dispatch_queue_create ("cn. xxx ", NULL); // Add the task to the serial queue and execute dispatch_sync (queue, ^ {NSLog (@" -------- download image 1 --------- % @", [NSThread currentThread]);}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 2 --------- % @", [NSThread currentThread]);}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 3 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download Image 4 --------- % @", [NSThread currentThread]) ;}); dispatch_sync (queue, ^ {NSLog (@ "-------- download image 5 --------- % @", [NSThread currentThread]) ;});}

One-time execution:

// One-time execution of static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// <# code to be executed once #> });
Delayed execution:
// Delayed execution (2 seconds) double delayInSeconds = 2; dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (delayInSeconds * NSEC_PER_SEC), interval (), ^ {// <# code to be executed after a specified delay #> });

Thread group: Concurrent execution threads in the background. The execution results will be summarized after all threads are executed.

// 1. Obtain the thread group dispatch_group_t group = dispatch_group_create (); // 2. Parallel Execution thread dispatch_group_async (group, queue, ^ {// concurrent execution thread 1 ); ispatch_group_async (group, queue, ^ {// concurrent execution thread 2}); // 3. Call dispatch_group_notify (group, queue, ^ {// Summary Result });
Inter-thread Communication

Return from sub-thread to main thread
Dispatch_async (
Dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Execute time-consuming asynchronous operations...
Dispatch_async (dispatch_get_main_queue (), ^ {
// Return to the main thread and perform the UI refresh operation
});
});

Example: download an image from a sub-thread and update the Image view on the page after the download.

-(Void) touchesBegan :( NSSet
 
  
*) Touches withEvent :( UIEvent *) event {dispatch_queue_t queue = queue (queue, 0); dispatch_async (queue, ^ {// The Sub-thread downloads the image NSURL * url = [NSURL URLWithString: @ "http://d.hiphotos.baidu.com/image/pic/item/37d3d539b6003af3290eaf5d362ac65c1038b652.jpg"]; NSData * data = [NSData dataWithContentsOfURL: url]; UIImage * image = [UIImage imageWithData: data]; // return to the main thread dispatch_queue_t mainQueue = Queue (); dispatch_async (mainQueue, ^ {self. imageView. image = image ;});});}
 

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.