IOS: The use of multithreading technology GCD

Source: Internet
Author: User
Tags gcd

Use of GCD:

1. Types of Queues1.1 Primary queue: Mian queue, Main thread queues, which are responsible for the operation of a more UI. is a serial queue. 1.2 system default parallel queue: Global queue, sorted by priority. 1.3 Custom Queues: You can create a serial queue or a parallel queue 2. Tasks2.1 Package Form: Block method or C-language function2.2 How to add to a queue: synchronous or asynchronous (differs only for parallel queues)For example, a server request:synchronization: Submit request, wait for the server to process (this period the client browser can not do anything), processing completed returnAsynchronous: Request through event triggered server processing (during which the client browser can still do other things)---processing completed return 3. Special Use3.1 Execute once dispatch_once (dispatch_once_t *predicate, dispatch_block_t block);(more for singleton mode)3.2 Delay Execution Dispatch_after (dispatch_time_t when,dispatch_queue_tqueue,dispatch_block_t block);3.3 dispatch_group_create (void) of the execution task of the group;3.4 Create a custom queue dispatch_queue_create (const char *label, dispatch_queue_attr_t attr);3.5 Create Default global queue Dispatch_get_global_queue (long identifier, unsigned long flags)3.6 Get home row dispatch_get_main_queue (void)3.7 Asynchronous ExecutionDispatch_async (dispatch_queue_t queue, dispatch_block_t block);3.8 Synchronous Execution Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block); 3.9 Multiple executions dispatch_apply (size_t iterations, dispatch_queue_t queue,void ( ^block) (size_t));.............. And so on ....... .......

4. Several method parameter explanations:

<1> Create a custom queue dispatch_queue_create (const char *label, dispatch_queue_attr_t attr);

const char *label: queue name dispatch_queue_attr_t attr: Queue execution Mode (asynchronous, synchronous)

<2> Create default global queue Dispatch_get_global_queue (long identifier, unsigned long flags)

Long identifier: Queue execution Priority unsigned long flags: default is 0

<3> multiple executions of dispatch_apply (size_t iterations, dispatch_queue_t queue,void (^block) (size_t));

size_t iterations: Number of executions dispatch_queue_t queue: queue void (^block) (size_t): block function blocks

 5. Queue way macro definition (parameters for creating a custom queue)

#define DISPATCH_QUEUE_SERIAL NULL//serial (synchronous)

#define Dispatch_queue_concurrent//parallel (asynchronous)

6. Queue priority macro definition (parameters when creating a global queue)

#define Dispatch_queue_priority_high 2

#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0

#define Dispatch_queue_priority_low (-2)

#define Dispatch_queue_priority_background Int16_min

7. More differentiated

Primary queue: A UI-specific update operation designed to perform the main thread

Global queue or Custom queue: used to add and execute other threads for data manipulation

Specific examples are as follows:

Example 1: In a non-grouped way, multithreading is added to the queue, and then multi-threaded operation.

1. Prepare the UI layout: Drag into a text view control and associate related classes, and declare a ticket variable in the class

@interface Viewcontroller () {    *TextView; @end

2. Set the number of votes, while emptying the default data in the original text view, cancel automatic layout to automatically scroll the text view when you add data later

// set up data and text views  - ; [Self.textview SetText: @""  = NO;

3. Create a global queue and set the priority

0);

4. Create the task thread with GCD and add the thread to the queue, using asynchronous execution

Dispatch_async (Queue, ^{        [self gcdsellticketmethod:@ "gcd ticket Thread-1"];    });     ^{        [self gcdsellticketmethod:@ 'gcd ticket Thread-2"];    }); 

5. Define how to update the UI

#pragma mark-Update UI action

-(void) Appendtextview: (NSString *) text{//1. Get the original dataNsmutablestring *content =[nsmutablestring StringWithString:self.textView.text]; Nsrange Range= Nsmakerange (Content.length,2); //2. Append new content[Content appendstring:[nsstring stringWithFormat:@"\n%@", text]];        [Self.textview settext:content]; //3. Scrolling the View[Self.textview scrollrangetovisible:range];}

6. Define how the task thread executes

#pragma mark-Perform a thread operation

-(void) Gcdsellticketmethod: (NSString *) name{ while(YES) {if(_tickets >0)        {            //using GCDDispatch_async (Dispatch_get_main_queue (), ^{                //Update UINSString *info = [NSString stringWithFormat:@"Total votes:%ld, current thread:%@", _tickets,name];                                [Self appendtextview:info]; //Sell Tickets_tickets--;                        }); //Thread Hibernation            if([Name isequaltostring:@"GCD Ticket Thread-1"]) {[Nsthread sleepfortimeinterval:0.3f]; }            Else{[Nsthread sleepfortimeinterval:0.2f]; }        }        Else        {            //updating the UI with GCDDispatch_async (Dispatch_get_main_queue (), ^{nsstring*info = [NSString stringWithFormat:@"tickets are sold out, current thread:%@", name];            [Self appendtextview:info];                        }); //Exit Thread             Break; }    }}

Example 2: Add a thread group to a queue in a grouped manner, and then perform multi-threaded operations.

1. Prepare the UI layout: Drag into a text view control and associate related classes, and declare a ticket variable in the class

@interface Viewcontroller () {    nsinteger _tickets;} @property (Weak, nonatomic) Iboutlet Uitextview *textview; @end

2. Set the number of votes, while emptying the default data in the original text view, cancel automatic layout to automatically scroll the text view when you add data later

//Set data and text view _tickets = 20; [Self.textview SetText:@ ""]; Self.textView.layoutManager.allowsNonContiguousLayout = NO;

3. Create a group of threads

dispatch_group_t group = Dispatch_group_create ();

4. Create a custom queue and set how the queue is executed in parallel (async)

dispatch_queue_t queue = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent);

5. Create a task thread group with GCD and add the thread group to the queue, using the group asynchronous execution method

Dispatch_group_async (Group,queue, ^{

[Self Gcdsellticketmethod:@ "GCD ticket thread-1"];

});

Dispatch_group_async (Group,queue, ^{

[Self Gcdsellticketmethod:@ "GCD ticket thread-2"];

});

6. When all tasks in the thread group are completed, you will receive a notification that updates the UI

Dispatch_group_notify (group, queue, ^{        ^{            *info = [NSString stringWithFormat:@ " The tickets are sold out . " ];            [Self appendtextview:info];        })    ;

7. Define how to update the UI

#pragma mark-Update UI action

-(void) Appendtextview: (NSString *) text{    //1. Get the original data    nsmutablestring *content = [nsmutablestring StringWithString:self.textView.text];    Nsrange range = Nsmakerange (content.length, 2);    //2. Append new content    [Content appendstring:[nsstring stringwithformat:@ "\n%@", text]];    [Self.textview settext:content];        //3. Scrolling view    [Self.textview Scrollrangetovisible:range];}

8. Define how the task thread executes

#pragma mark-Perform a thread operation

-(void) Gcdsellticketmethod: (NSString *) name{while (YES) {if (_tickets > 0) {//Use GCDDispatch_async (Dispatch_get_main_queue (), ^{//Update UINSString *info = [NSString stringWithFormat:@ "Total votes:%ld, Current thread:%@", _tickets,name]; [Self appendtextview:info];//Sell tickets_tickets--; });//thread hibernationif ([Name isequaltostring:@ "GCD ticket thread-1"]) {[Nsthread sleepfortimeinterval:0.3f];            } else {[Nsthread sleepfortimeinterval:0.2f]; }} else {//Exit threadBreak }    }}

The results of the two scenarios are as follows:

IOS: The use of multithreading technology GCD

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.