IOS GCD nsoperation Nsthread, etc. multi-Threading various examples (copy)

Source: Internet
Author: User
Tags gcd

More than 2 years of the path of iOS hurried over, during the period also read a lot of great God's blog, recently suddenly for their own have been doing the party feel ashamed, it is time to repay the community. Back when I was still small white when, according to some of the iOS multi-threaded tutorial, also just copied, only know it, do not know why. Now write a detailed tutorial dedicated to the vast number of readers. Nonsense is not much to say, directly on the dry. such as the list of many multi-threaded knowledge points, each knowledge point is written with a corresponding detailed example, and the results of the analysis of the operation, absolutely take the results of practice to speak. Please correct me if you find the wrong point. Attach Demo

Comparison of several multithreading in iOS

  GCD: It is the solution that Apple proposes for multi-core parallel operation, so it automatically makes use of more CPU cores (such as dual-core, quad-core), and most importantly, it automatically manages the thread's life cycle (creating threads, dispatching tasks, destroying threads), and does not require us to manage them at all.

  nsoperation: Apple's encapsulation of GCD, which encapsulates what needs to be done in an object-oriented manner, without concern for thread management, synchronization, and so on. Nsoperation and Nsoperationqueue correspond to GCD tasks and queues respectively.

  Nsthread: There are three methods that are relatively lightweight, but need to manage the lifecycle, synchronization, and locking of threads, which can lead to some performance overhead.

One, iOS multi-thread GCD Chapter 1. Serial queuing executes asynchronously (without blocking the current thread, and is executed sequentially, the previous one completes, the latter begins, and the asynchronous operation opens another thread)

As an example,

Serial Queue asynchronous execution-(ibaction) Serialasync: (ID) Sender {    //Create a serial queue    ///Where the first parameter is the identifier. The second argument passes dispatch_queue_serial or NULL to create a serial queue, and an incoming dispatch_queue_concurrent represents the creation of a parallel queue.    dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", NULL);    10 time-consuming asynchronous tasks are added to the serial queue for    (nsinteger n = 0; n < 3; n++) {        dispatch_async (myqueue, ^{//) with a for loop to            simulate a time-consuming operation            for (Nsinteger i = 0; i < 500000000; i++) {                if (i = = 0) {                    NSLog (@ "Serial asynchronous task%ld%@", N,[nsthread Curren TThread]);                }                if (i = = 499999999) {                    NSLog (@ "Serial asynchronous task%ld--Complete", (long) n);}}        )    ;    } NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Analysis conclusion: "Did you block me?" "This is printed on the first line, stating that the serial asynchronous operation does not block the current thread, and is executed sequentially, before the last one is completed and the latter only begins. An asynchronous operation will open another thread.

2. Serial Queue synchronous Execution (will block the current thread, and are executed sequentially, the previous one is completed, the latter only starts, the synchronization operation does not open threads)

As an example,

Serial Queue Synchronous Execution-(ibaction) Serialsync: (ID) Sender {    //Create a serial queue    ///Where the first parameter is the identifier. The second argument passes dispatch_queue_serial or NULL to create a serial queue, and an incoming dispatch_queue_concurrent represents the creation of a parallel queue.    dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", NULL);    10 time-consuming synchronization tasks are added to the serial queue for    (nsinteger n = 0; n < 3; n++) {        dispatch_sync (myqueue, ^{//analog) with a For loop for            a time-consuming operation C8/>for (Nsinteger i = 0; i < 500000000; i++) {                if (i = = 0) {                    NSLog (@ "Serial synchronization task%ld start%@", N,[nsthread Curren TThread]);                }                if (i = = 499999999) {                    NSLog (@ "Serial synchronization task%ld-to-Finish", (long) n);}}        );    } NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Analysis conclusion: "Did you block me?" "This is the end of the sentence, which indicates that the serial queue synchronization task blocks the current thread and is executed sequentially, the previous one is completed, and the latter begins. From the printing results, all in the main thread execution, so the synchronization operation will not open the thread.

3. Parallel queues are executed asynchronously (without blocking the current thread, multiple tasks start at the same time, asynchronous operations open another thread)

As an example,

Parallel queue Asynchronous execution-(ibaction) Concurrentasync: (ID) Sender {    //Create a parallel queue    ///Where the first parameter is an identifier. The second argument passes dispatch_queue_serial or NULL to create a serial queue, and an incoming dispatch_queue_concurrent represents the creation of a parallel queue.    dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent);    10 time-consuming asynchronous tasks are added to the parallel queue for    (nsinteger n = 0; n < 3; n++) {        dispatch_async (myqueue, ^{//simulation) with a for loop for            a time-consuming operation            for (Nsinteger i = 0; i < 500000000; i++) {                if (i = = 0) {                    NSLog (@ "Parallel asynchronous task%ld start%@", N,[nsthread Curren TThread]);                }                if (i = = 499999999) {                    NSLog (@ "Parallel asynchronous task%ld-Complete", (long) n);}}        );    } NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Analysis Conclusion: The current thread is not blocked, the time of the red circle is displayed, and the parallel queue asynchronous multiple tasks begin simultaneously. An asynchronous operation will open another thread.

4. Parallel queue execution (which blocks the current thread, is executed sequentially, the previous one completes, and the latter begins.) )

As an example,

Parallel queue Synchronous Execution-(ibaction) Concurrentsync: (ID) Sender {    //Create a parallel queue    ///Where the first parameter is an identifier. The second argument passes dispatch_queue_serial or NULL to create a serial queue, and an incoming dispatch_queue_concurrent represents the creation of a parallel queue.    dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent);    10 time-consuming synchronization tasks are added to the parallel queue for    (nsinteger n = 0; n < 3; n++) {        dispatch_sync (myqueue, ^{//) through a For loop for            a time-consuming operation C8/>for (Nsinteger i = 0; i < 500000000; i++) {                if (i = = 0) {                    NSLog (@ "Parallel synchronization task%ld start%@", (long) N,[nsthread CurrentThread]);                }                if (i = = 499999999) {                    NSLog (@ "Parallel synchronization task%ld-Complete", (long) n);}}        );        } NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Analysis Conclusion: Parallel queue synchronization execution will block the current thread. and are executed sequentially, the previous one is completed, and the latter one begins. (Note: Here the sequential one executes and the serial queue is different, here is because the synchronization operation will block the current thread, from the printing results see that these three operations are in the main thread, when the first operation is completed, the thread is unblocked, and then the next, and then one execution) from the print results, all in the main thread execution, So the synchronization task does not open threads.

5. Summary of synchronous asynchronous and serial parallelism

In the past 4 examples small conclusion: a. Serial queues, whether asynchronous or synchronous, are executed one after the other; B. Synchronous operations, whether parallel or serial, are performed sequentially one by one (but synchronous operations are performed in parallel and serially in sequential order because the reason for one execution is different, see GCD4 for an analysis of the example). C. Synchronous operations will open up threads, and asynchronous operations do not open threads;

6. Queue Group (when all the tasks in the group have been executed, the queue group notifies us through a method that executes asynchronously in parallel without blocking the current thread)

As an example,

Queue Group-(ibaction) Queuegroup: (ID) Sender {//Create queue group dispatch_group_t group = Dispatch_group_create (); Create global parallel queue dispatch_queue_t globalqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);
Create a custom parallel queue dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent);
Create the home row dispatch_queue_t mainqueue = Dispatch_get_main_queue (); The queue group executes the global queue Dispatch_group_async (group, Globalqueue, ^{for (Nsinteger i = 0; i < 3; i++) {NSLog ( @ "Global parallel queue%ld", (long) i); } }); Queue Group Execution custom parallel queue Dispatch_group_async (group, Myqueue, ^{for (Nsinteger i = 0; i < 4; i++) {NSLog (@ "Custom parallel Queue%ld", (long) i); } }); The queue group executes the home column Dispatch_group_async (group, Mainqueue, ^{for (Nsinteger i = 0; i < 5; i++) {NSLog (@ "Primary Queue%ld ", (long) i); } }); Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{NSLog (@ "Finish-%@", [Nsthread CurrentThread]); }); NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Conclusion: When all the tasks in the group are executed, the queue group notifies us by a method that executes asynchronously in parallel without blocking the current thread.

7.GCD delay

As an example,

GCD delay-(ibaction) Dispatchdelay: (ID) Sender {    //non-blocking execution mode    double delayinseconds = 2.0;    dispatch_time_t poptime = Dispatch_time (Dispatch_time_now, delayinseconds * nsec_per_sec);    Dispatch_after (Poptime, Dispatch_get_main_queue (), ^ (void) {        NSLog (@ "Delayed 2 seconds");    });        Since the delay delay, it is compared with the other several delay        //1. This method requires that it must be executed in the main thread, otherwise it is not valid. is a non-blocking method of execution that has not yet been found to cancel execution.    [Self performselector: @selector (Delaymethod) Withobject:nil afterdelay:1.0f];        2. This method requires that it must be executed in the main thread, otherwise invalid. is a non-blocking execution method that can be invalidate by the Nstimer class-(void);    [Nstimer scheduledtimerwithtimeinterval:1.0f target:self selector: @selector (Delaymethod) Userinfo:nil Repeats:no];        3. This method can be executed in both the main thread and the child thread. is a blocking method of execution, which is placed in a sub-thread, so as not to get stuck in the interface, no way to cancel execution.    [Nsthread sleepfortimeinterval:4.0f];//    [self delaymethod];           NSLog (@ "Blocking me?" Current thread%@ ", [Nsthread CurrentThread]);}

Printing results:

Analysis Conclusion: The GCD delay does not block the current thread, and the deferred operation is performed on the child thread

8.dispatch_barrier_async (The previous task is complete before performing a later task)

As an example,

-(Ibaction) wait: (ID) Sender {dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent);            Add 2 tasks in front for (nsinteger n = 0; n < 2; n++) {Dispatch_async (myqueue, ^{//simulates a time-consuming operation for (Nsinteger i = 0; i < 500000000; i++) {if (i = = 0) {NSLog (@ "Before task%ld, start"                , (long) n);                } if (i = = 499999999) {NSLog (@ "Complete before task%ld," (long) n);    }            }        });    } dispatch_barrier_async (Myqueue, ^ () {NSLog (@ "Dispatch-barrier");        }); Add 2 tasks for (Nsinteger n = 0; n < 2; n++) {Dispatch_async (myqueue, ^{//simulates a time-consuming operation F or (Nsinteger i = 0; i < 500000000; i++) {if (i = = 0) {NSLog (@ "After task%ld, start" (l                ONG) n);               } if (i = = 499999999) {NSLog (@ "after" Task%ld, "(long) n); }            }        }); }}

Printing results:

Analysis Conclusion: The Dispatch_barrier_async method blocks the queue (note that blocking the queue, not blocking the current thread) waits until the task in front of it in the queue is executed in parallel and executes itself after execution. Cancel the blocking so that the task behind it in the queue continues to execute in parallel. (Note: If you pass in another queue, it will be the same as Dispatch_async.) )

9. Deadlock Main Thread

As an example,

Deadlock main thread-(ibaction) DEADLOCK1: (ID) Sender {    NSLog (@ "The front-%@", [Nsthread CurrentThread]);    Dispatch_sync (Dispatch_get_main_queue (), ^{        NSLog (@ "Thread of synchronous operation-%@", [Nsthread CurrentThread]);    });    NSLog (@ "After thread-%@", [Nsthread CurrentThread]);}

Printing results:

Analysis Conclusion: Only printed a sentence, found that the back of two did not print out, the explanation has been deadlocked. We take a step-by-step analysis, after printing the first sentence, the synchronization operation Dispatch_sync immediately block the current main thread, and then put the task in the Block into the Main_queue, and then the Main_queue in the task will be removed to put in the main thread to execute, But the main thread this time has been blocked, so the task in block can not be completed, it is not completed, Dispatch_sync will always block the main thread, this is the deadlock phenomenon. Causes the main thread to remain stuck.

10. Deadlock Child Thread

As an example,

Deadlock Child Thread-(ibaction) Deadlock2: (ID) Sender {    dispatch_queue_t myqueue = dispatch_queue_create ("Myqueue", NULL);    NSLog (@ "The front-%@", [Nsthread CurrentThread]);    Dispatch_async (Myqueue, ^{        NSLog (@ "Synchronous operation of the front path-%@", [Nsthread CurrentThread]);        Dispatch_sync (Myqueue, ^{            NSLog (@ "Synchronous operation Thread-%@", [Nsthread CurrentThread]);        });        NSLog (@ "Sync operation after thread-%@", [Nsthread CurrentThread]);    });    NSLog (@ "After thread-%@", [Nsthread CurrentThread]);}

Printing results:

Analysis Conclusion: After printing the first sentence is an asynchronous operation, the asynchronous operation will open another thread, 2 threads each print the last sentence and the second sentence, when the execution to the synchronization operation Dispatch_sync immediately block the current thread, wait until the task in sync will continue to run down. Sync then puts the task in the block into the queue, but the queue is a serial queue and performs one task at a time, so the block of sync must wait until the previous task is completed, but the queue is performing the task of being blocked by sync. And then there was a deadlock. So the thread where sync is stuck is dead. The remaining two lines of code will naturally not print.

Two, multi-thread nsoperation article

See my other blog. iOS multi-thread nsoperation article examples

Three, multi-thread Nsthread article

See my other blog. iOS multi-thread Nsthread article examples

IOS GCD nsoperation Nsthread, etc. multi-Threading various examples (copy)

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.