An analysis of the results of permutations and combinations of queues and executions in iOS multi-threading

Source: Internet
Author: User

This paper is a collation of knowledge points in multi-threading in previous studies.

Queues in multiple threads are: serial queue, concurrent queue, global queue, home row .

The methods performed are synchronous execution and asynchronous execution . So what are the considerations for the 221 combination?

If you don't see this article in the Dong Platinum Blog Park, please click here to view the original

Refers to multi-threading, that is, four kinds, pthread,nsthread,gcd,nsoperation

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

But the difference: the core concept of GCD is to add a task to the queue , specify the method that the task executes, and then execute it. The nsoperation is to add an operation directly to the queue .

For the whole structure to be clearer, I used the GCD to do this sort of combination experiment. The experiment is to judge the result by the sequence of printing in the loop and the main thread, and then summarize it.

1. Serial queue, synchronous execution
    dispatch_queue_t q = dispatch_queue_create ("Dantesx", NULL);        Perform a task for    (int i = 0; i<10; i++) {        dispatch_sync (q, ^{            NSLog (@ "%@%d", [Nsthread CurrentThread], i);        });    }        NSLog (@ "Dong Platinum come Here");

Operating effect:

Execution results can be clearly seen all in the main thread execution, and is executed in sequence, after the end of the loop to print the main thread 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");

Run results

The result shows that the system has 1 asynchronous threads open, so all thread 2 executes and is executed sequentially. The main thread is printed in the top, but this sequence is not sure, if you sleep for 0.001 seconds, the main thread of the printing will be mixed in the middle.

3. Concurrent queues, asynchronous execution
    1. Queue    dispatch_queue_t q = dispatch_queue_create ("Dantesx", dispatch_queue_concurrent);        2. Asynchronously executes for    (int i = 0; i<10; i++) {        dispatch_async (q, ^{            NSLog (@ "%@%d", [Nsthread CurrentThread], i);        } );    }    [Nsthread sleepfortimeinterval:2.0];    NSLog (@ "Dong Platinum come Here");

Run results

The results show that the main thread of the printing is still mixed in the middle of the uncertainty, because the asynchronous thread is who does not wait for WHO. The system opens multiple threads, and the order of execution is chaotic.

4. Concurrent queue, synchronous execution
    1. Queue    dispatch_queue_t q = dispatch_queue_create ("Dantesx", dispatch_queue_concurrent);        2. Synchronous execution for    (int i = 0; i<10; i++) {        dispatch_sync (q, ^{            NSLog (@ "%@%d", [Nsthread CurrentThread], i);        }) ;    }    [Nsthread sleepfortimeinterval:2.0];    NSLog (@ "Dong Platinum come Here");

Run results

The result of this operation is identical to the 1th serial queue, which executes synchronously. Because the concept of synchronous tasks is executed sequentially, and so on later. The implication is that multiple threads are not allowed. Synchronous and asynchronous is the decision to open a bar or open more than one.

So once the synchronization is performed, there is no difference in what queue is ahead .

5. Home row, asynchronous execution
    1. Primary queue-The main thread already exists after the program starts, and the home row also exists    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 (@ "slumber");    [Nsthread sleepfortimeinterval:2.0];    NSLog (@ "Dong Platinum come Here");

Run results

The results are a little surprising. The main thread does not print until after sleep, and the loop is waiting. Because the task of the home row is added to the main thread, if the main thread thread also has a task, it must wait for the main thread to finish executing before it turns to the primary queue .

6. Home row, synchronous execution
    dispatch_queue_t q = Dispatch_get_main_queue ();        NSLog (@ "is the card dead?" ");        Dispatch_sync (q, ^{        NSLog (@ "I'm Coming");    });        NSLog (@ "Dong Platinum come Here");

The result of the operation is a dead card

The cause of the death is the loop waiting , the main line of things to wait for the primary thread to finish, and because it is synchronous execution can not be the thread, so the following tasks to wait for the above task to finish, so the card is dead. This is the only combination of the permutations that will die.

7. Usage Scenarios for synchronization Tasks
    dispatch_queue_t q = dispatch_queue_create ("Dantesx", dispatch_queue_concurrent);    1. User login, must be the first to execute    dispatch_sync (q, ^{        [Nsthread sleepfortimeinterval:2.0];        NSLog (@ "User login%@", [Nsthread CurrentThread]);    });    2. Deduction fee    Dispatch_async (q, ^{        NSLog (@ "Deduction%@", [Nsthread CurrentThread]);    });    3. Download    dispatch_async (q, ^{        NSLog (@ "Download%@", [Nsthread CurrentThread]);    });    NSLog (@ "Dong Platinum come Here");

Run results

The results show that "user login" is printed on the main thread, and the latter two are printed on the async threads. The "User Login" above uses synchronous execution, and subsequent charges and downloads are performed asynchronously. So "User Login" must first print out no matter how long it takes, then the two async and main thread later print will be printed in an indeterminate order. This is the daily development, those who have dependencies on it must perform the task first , and then perform the order anyway, regardless of the use of asynchronous execution.

8.block Asynchronous Task wrap synchronization task
    dispatch_queue_t q = dispatch_queue_create ("Dantesx", dispatch_queue_concurrent);    void (^task) () = ^ {        //1. User login, must be the first to execute        dispatch_sync (q, ^{            NSLog (@ "User login%@", [Nsthread CurrentThread]); 
   });        2. Deduction fee        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");

Run results

Because the entire block is executed asynchronously, even if the "user login" is executed synchronously, it can not be executed in the main thread, only open an asynchronous thread execution, because it is synchronous, so he must wait for him to execute first, after the "deduction" and "Download" in the above synchronous execution, after the end of the sequence is not determined to print.

9. Global Queue
    dispatch_queue_t q = dispatch_get_global_queue (0, 0);        for (int i = 0; i < i++) {        dispatch_async (q, ^{            NSLog (@ "%@%d", [Nsthread CurrentThread], i);        });    }    [Nsthread sleepfortimeinterval:1.0];    NSLog (@ "com here");

Run results

The essence of the global queue is the concurrent queue , just after the addition, "quality of Service", and "scheduling priority" two parameters, these two parameters generally for the adaptation between the system, it is best to fill in 0 and 0 directly.

If you don't see this article in the Dong Platinum Blog Park, please click here to view the original

Summary:

1. Open the thread, depending on the function of the execution of the task, synchronization is not open, asynchronous open.

2. Open a few threads, depending on the queue, serial open a line, and open multiple (asynchronous)

3. Home column: A "queue" dedicated to scheduling tasks on the main thread, the home column cannot dispatch tasks in other threads!

4. If a task is currently being performed on the main thread, the home column will not dispatch the execution of the task temporarily! The primary queue synchronization task causes a deadlock. The reason is that the loop waits

5. The synchronization task can queue up multiple asynchronous tasks, specify a synchronization task, and let all asynchronous tasks wait for the synchronization task to complete, which is the dependency relationship.

6. Global queue: concurrency, ability to schedule multiple threads, high execution efficiency, but relatively low power costs. The serial queue is inefficient, saves power, or requires dependencies between tasks and can use a serial queue.

7. You can also determine the number of threads to open by judging the current user's network environment. WiFi under 6, 3g/4g under two or three.

An analysis of the results of permutations and combinations of queues and executions in iOS multi-threading

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.