Result Analysis of queues and execution in iOS multithreading, and ios Multithreading

Source: Internet
Author: User

Result Analysis of queues and execution in iOS multithreading, and ios Multithreading

This article aims to organize the knowledge points in the multi-thread model that we have learned in the past.

Queues in multiple threads include:Serial queue, concurrent queue, global queue, and main queue.

The execution methods include:Synchronous execution and asynchronous execution. So what are the precautions for a combination of two or two?

If you do not see this article in Dong Boran's blog Park, click to view the original article.

Multithreading, pthread, NSthread, GCD, and NSOperation

Phtread is cross-platform. GCD and NSOperation are both common, and the latter is based on the former.

But the difference between the two: the core concept of GCD is to add a task to the queue, specify the method for executing the task, and then execute it. NSOperation directly adds an operation to the queue.

To make the overall structure clearer, I used GCD for the experiment of this arrangement and combination. The experiment mainly judges the results through the print sequence of the loop and the main thread, and summarizes the results.

1. Serial queue, synchronous execution
Dispatch_queue_t q = dispatch_queue_create ("dantesx", NULL); // execute the task for (int I = 0; I <10; I ++) {dispatch_sync (q, ^ {NSLog (@ "% @ % d", [NSThread currentThread], I) ;};} NSLog (@ "Dong platinum come here ");

Running effect:

 

The execution results clearly show that all tasks are executed in the main thread and are executed in the order of numbers. After the loop ends, the printing of the main thread is output.

2. Serial queue, asynchronous execution
Dispatch_queue_t q = dispatch_queue_create ("dantesx", NULL); for (int I = 0; I <10; I ++) {dispatch_async (q, ^ {NSLog (@ "% @ % d", [NSThread currentThread], I) ;}// [NSThread sleepForTimeInterval: 0.001]; NSLog (@ "Dong platinum come here ");

Running result

The result shows that the system has an asynchronous thread, so all threads are executed in the order of thread 2. Although the printing of the main thread is at the top, the order is uncertain. If you sleep for 0.001 seconds, the printing of the main thread will be mixed in the middle.

3. Concurrent queue, asynchronous execution
// 1. queue dispatch_queue_t q = dispatch_queue_create ("dantesx", DISPATCH_QUEUE_CONCURRENT); // 2. asynchronous execution of for (int I = 0; I <10; I ++) {dispatch_async (q, ^ {NSLog (@ "% @ % d", [NSThread currentThread], i) ;}) ;}// [NSThread sleepForTimeInterval: 2.0]; NSLog (@ "Dong platinum come here ");

Running result

The results show that the printing of the main thread is not clear in the middle, because the asynchronous thread is not waiting for anyone. The system has opened multiple threads and the execution order is also out of order.

 

4. Concurrent queue, synchronous execution
// 1. queue dispatch_queue_t q = dispatch_queue_create ("dantesx", DISPATCH_QUEUE_CONCURRENT); // 2. synchronously execute for (int I = 0; I <10; I ++) {dispatch_sync (q, ^ {NSLog (@ "% @ % d", [NSThread currentThread], i) ;}) ;}// [NSThread sleepForTimeInterval: 2.0]; NSLog (@ "Dong platinum come here ");

Running result

The running result is exactly the same as that of the 1st serial queues. Because the concept of a synchronization task is to execute it in order, it will be waited for later. The implication is that multiple threads are not allowed. Synchronization and Asynchronization determine whether to open one or more.

So once it is executed synchronously, there is no difference in the queue above.

5. the queue is asynchronously executed.
// 1. main queue column-the main thread already exists after the program is started, and the main queue column also has dispatch_queue_t q = dispatch_get_main_queue (); // 2. schedule a task for (int I = 0; I <10; I ++) {dispatch_async (q, ^ {NSLog (@ "% @ % d", [NSThread currentThread], i) ;}) ;}nslog (@ "Sleep"); [NSThread sleepForTimeInterval: 2.0]; NSLog (@ "Dong platinum come here ");

Running result

The results are somewhat surprising. The main thread is printed after sleep, And the loop is always waiting. Although the tasks in the main thread column are added to the main thread for execution, if there are also tasks in the main thread, the main thread must wait until the main thread task is executed.

6. The master column is synchronized.
Dispatch_queue_t q = dispatch_get_main_queue (); NSLog (@ "Is it stuck? "); Dispatch_sync (q, ^ {NSLog (@" I'm Coming ") ;}); NSLog (@" Dong platinum come here ");

The running result is stuck.

The reason for the interruption is loop wait. The main queue columns have to wait for the main thread to complete the execution, but because synchronous execution cannot start the thread, the following tasks have to wait until the preceding tasks are completed, so they are stuck. This is the only combination in the permutation and combination that will be stuck.

7. Use Cases of synchronization tasks
Dispatch_queue_t q = dispatch_queue_create ("dantesx", DISPATCH_QUEUE_CONCURRENT); // 1. user Logon. You must first execute dispatch_sync (q, ^ {[NSThread sleepForTimeInterval: 2.0]; NSLog (@ "User Logon % @", [NSThread currentThread]);}); // 2. deduction dispatch_async (q, ^ {NSLog (@ "deduction % @", [NSThread currentThread]);}); // 3. download dispatch_async (q, ^ {NSLog (@ "Download % @", [NSThread currentThread]) ;}); NSLog (@ "Dong platinum come here ");

Running result

The results show that "User Login" is printed in the main thread, and the last two are printed in the asynchronous thread. The above "User Login" uses synchronous execution, and the subsequent fee deduction and download are both asynchronous execution. Therefore, "User Login" must be printed first no matter how long it takes, and the subsequent two asynchronous and main threads will print in an uncertain order. This is what happens in daily development. The tasks that must be executed first must be executed synchronously in the face of their dependencies, and asynchronous execution is used in order of order.

8. block asynchronous task package synchronization task
Dispatch_queue_t q = dispatch_queue_create ("dantesx", DISPATCH_QUEUE_CONCURRENT); void (^ task) () = ^ {// 1. user Logon. You must first execute dispatch_sync (q, ^ {NSLog (@ "User Logon % @", [NSThread currentThread]);}); // 2. deduction dispatch_async (q, ^ {NSLog (@ "deduction % @", [NSThread currentThread]);}); // 3. download dispatch_async (q, ^ {NSLog (@ "Download % @", [NSThread currentThread]) ;}; dispatch_async (q, task); [NSThread sleepForTimeInterval: 1.0]; NSLog (@ "Dong platinum come here ");

Running result

Because the entire block is executed asynchronously, even if "User Login" is executed synchronously, it cannot be executed in the main thread. Only one asynchronous thread can be run, because it is synchronous, it is necessary to wait for him to execute it first. The "deduction" and "Download" following will be printed in an uncertain order after the synchronization is completed.

9. Global queue
    dispatch_queue_t q = dispatch_get_global_queue(0, 0);        for (int i = 0; i < 10; i++) {        dispatch_async(q, ^{            NSLog(@"%@ %d", [NSThread currentThread], i);        });    }    [NSThread sleepForTimeInterval:1.0];    NSLog(@"com here");

Running result

The essence of a global queue is a concurrent queue. It is only added to the backend. "service quality" and "scheduling priority" parameters are generally used for system adaptation, it is best to enter 0 and 0 directly.

If you do not see this article in Dong Boran's blog Park, click to view the original article.

Summary:

1. The thread cannot be opened. It depends on the function used to execute the task. The synchronous thread cannot be opened and the asynchronous thread is enabled.

2. Several threads are opened, depending on the queue. One thread is serialized and multiple threads are concurrently opened (asynchronous)

3. Main queue column: it is a "queue" dedicated to scheduling tasks on the main thread. The main queue Column cannot schedule tasks in other threads!

4. If a task is being executed on the main thread, the main queue will not schedule the task execution for the moment! The synchronization task of the main queue column may cause deadlocks. The reason is loop wait.

5. Before a synchronization task can be scheduled in a queue for multiple asynchronous tasks, specify a synchronization task to allow all asynchronous tasks to wait until the synchronization task is completed. This is dependency.

6. Global queue: Concurrent, able to schedule multiple threads, high execution efficiency, but relatively low power consumption. The serial queue is inefficient, saves power and saves traffic, or requires dependencies between tasks. You can also use serial queues.

7. You can also determine the number of threads opened by judging the current user's network environment. 6 under WIFI, 2 under 3G/4G ~ 3.

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.