"IOS" Multithreading gcd

Source: Internet
Author: User

GCD(Grand Central Dispatch) : the backbone scheduler. Apple comes with a pure C language implementation, providing a very large and powerful function that can improve code execution efficiency and multicore utilization.

First, the basic use of GCD

1.GCDin thetwo coresConcept:?Task: what tasks to perform.?Queue: used to store tasks. (used to dispatch tasks)2.GCDused by2a step:?1.AvailabilitysystemTask. (identify the things you want to do)?2.will beTask Addinto the queue.?GCDwill beautomaticallywill beQueuethe tasks inremoved,put inthe corresponding threadexecuted in.?follow the queue'sFIFOPrinciples:Advanced First Out.3.Synchronous and asynchronousthe Difference: (whether to open a new thread)?Sync:executes in the current thread.?Asynchronous:executing in another thread.4, parallel and serial queue : (How the task is executed) ? Parallel pairs of columns:in theAsynchronouscases of,Make multiple TasksConcurrent Execution.?Serial Queue:a taskwhen you are finished executing,re-executeNext Task.
queues are divided into several categories: custom queues, global queues, home rowThe basic usage code is as follows:

-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{[self GcdDemo4];} #pragma mark-serial queue-(void) gcddemo1{//1. Serial queue//When using GCD, first knock dispatch//In the C language, the definition object is usually the end of _t or Ref Dispat ch_queue_t q = dispatch_queue_create ("Myqueuename", dispatch_queue_serial);        The value of dispatch_queue_serial is NULL NSLog (@ "%@", [Nsthread CurrentThread]); 2. Sync task Sync (useless in real development) for (int i = 0; i < i++) {Dispatch_sync (q, ^{NSLog (@ "%@-%d", [Nsthread        CurrentThread], i);    }); }//2.    Async Task Async, able to open the thread//serial queue, the asynchronous task can be opened at most one threads, all tasks executed sequentially!    Serial queue, asynchronous task, in multi-threading, is the most recommended multi-threaded way of Stanford University!    Pros: Put tasks on other threads, execute each task sequentially, facilitate debugging//cons: Not strong concurrency, only one thread at most!        for (int i = 0; i < i++) {Dispatch_async (q, ^{NSLog (@ "%@-%d", [Nsthread CurrentThread], i);    }); }} #pragma mark-parallel queue-(void) gcddemo2{//1. Parallel queue dispatch_queue_t q = dispatch_queue_create ("Myqueuename", dispatch        _queue_concurrent); Non-arc, you need to release the queue yourself//dispatch_release (q); 2.  Synchronization task, does not open a new thread//in real development, the synchronization task can ensure that the execution is completed before the subsequent asynchronous task to start execution, to control the order between tasks, such as in the background thread, processing "User login" and so on for (int i = 0; i < i++)        {Dispatch_sync (q, ^{NSLog (@ "%@-%d", [Nsthread CurrentThread], i);    }); }//3.    Asynchronous tasks that will work on multiple threads, how many threads to open, are scheduled by the system//are still in the order in which the tasks are added to the queue, but the execution may differ! Ability to put time-consuming operations into child threads//* * * * * * * compared to serial queue asynchronous task, concurrency performance is better! But the order of execution is not fixed for (int i = 0; i < i++) {Dispatch_async (q, ^{NSLog (@ "%@-%d", [Nsthread Curr        Entthread], i);    }); }} #pragma mark-Global parallel (concurrent) queue (with more common)-(void) gcddemo3{//1. Get a global queue (unlike a custom parallel queue, the name is displayed, the others are the same) dispatch_queue_t q = di    Spatch_get_global_queue (dispatch_queue_priority_default, 0); With global queues, there is no need to consider shared issues//2. Synchronization task for (int i = 0; i < i++) {Dispatch_sync (q, ^{NSLog (@ "%@-%d", [Nsthread CurrentThread]        , i);    }); }//3. asynchronous task for (int i = 0; i < i++) {DIspatch_async (q, ^{NSLog (@ "%@-%d", [Nsthread CurrentThread], i);    }); }} #pragma mark-the home row (a queue that is specifically scheduled to work on the main thread, not thread)-(void) gcddemo4{//1. Get the home row dispatch_queue_t q = dispatch_get_main_queue        (); 2. Do not synchronize tasks (Deadlock!!!)    )//Dispatch_sync (Q, ^{//NSLOG (@ "!!! Not output");        //    }); 3. asynchronous tasks, sequentially executing for (int i = 0; i < i++) {Dispatch_async (q, ^{NSLog (@ "%@-%d") on the main thread, [Nsthread C        Urrentthread], i);    }); }}

Second, GCD for inter-thread communication

Here, the method of downloading a picture is called from the main thread, a thread is opened for download, and then the thread is returned to the main path after the task is completed.

-(void) downloadimage{    //1. Global Parallel queue    dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_ Priority_default, 0);        2. Asynchronous task    Dispatch_async (queue, ^{        NSLog (@ "Start download picture%@", [Nsthread CurrentThread]);        。。。。        NSLog (@ "Complete download picture%@", [Nsthread CurrentThread]);                3. Notifies the host column to update the UI//to the Home        column, add an asynchronous task, update UI        Dispatch_async (Dispatch_get_main_queue (), ^{            //Can do the update UI action ....        });    });}


The following 2 articles are good and can be better understood:
http://blog.csdn.net/onlyou930/article/details/8225906

Http://www.cnblogs.com/pure/archive/2013/03/31/2977420.html


Reprint Please specify Source: http://blog.csdn.net/xn4545945






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.