Multi-Threading for iOS development

Source: Internet
Author: User

1 , Multithreading Concepts

Process

A program that is in progress is called a process that is responsible for the memory allocations that the program runs. Each process has its own independent virtual memory space.

Thread

A thread is a separate execution path in the process (Control unit)

At least one thread is included in a process, that is, the main path

You can place time-consuming execution paths (such as network requests) on other threads

The purpose of creating a thread is to open a new execution path, run the specified code, and run concurrently with the code implementation in the main thread.

Stack area : 1M of the main thread stack area, very very valuable. A process that has at least one thread (the main path) and cannot kill a thread! However, you can pause and hibernate.

2 , multi-tasking system scheduling

Description: Each application is allocated by the operating system for a short time slice (timeslice) in turn using the CPU, since the CPU is processing each time slice very fast, so the user looks as if these tasks are executing simultaneously.

Concurrency: Two or more tasks occur within the same interval, but at any point in time, the CPU only processes one task.

3 , advantages, disadvantages and misunderstandings

Advantage:

(1) Give full play to the multi-core processor advantage, assign different thread tasks to different processors and really enter the "parallel operation" state

(2) Assigning time-consuming tasks to other threads, responsible for unifying the update interface by the main thread, makes the application smoother and the user experience better

(3) When the number of hardware processors increases, the program runs faster and the program does not need to make any adjustments

Malpractice :

New threads consume memory space and CPU time, and too many threads can degrade system performance

misunderstanding :

Multithreading is designed to perform multiple tasks concurrently, without increasing the efficiency of the individual algorithm itself.

4 , IOS three kinds of multithreading technology

Nsthread

(1) It is very convenient to build a thread using the Nsthread object

(2) but! It is very difficult to manage multiple threads using Nsthread, it is not recommended to use

(3) Tips! Get tasks online using [Nsthread CurrentThread] for these three technologies

(4) the thread sleeps 0.3 seconds:[Nsthread sleepfortimeinterval:0.3f];

Nsoperation/nsoperationqueue

(1) is a set of OBJECTIVE-C APIs implemented using GCD

(2) is an object-oriented threading technology

(3) provides some features that are not easy to implement in GCD, such as limiting the maximum number of concurrent and the dependencies between operations

Gcd--grand Central Dispatch

(1) is a C-based underlying API

(2) Define the task with block, which is very flexible and convenient to use.

(3) provides additional control capabilities and underlying functions that are not available in the Operation queue

Tip:iOS developers need to be aware of the basic use of three multithreaded technologies, as the actual development will be based on the actual choice of different multithreading technology.

4 , GCD Basic Ideas

The basic idea of GCD is to put the operation s in the queue s to execute.

(1) Operation using blocks definition

(2) The queue is responsible for scheduling the thread on which the task executes and the specific execution time

(3) The queue is characterized by FIFO, and new additions to the column will be queued at the end of the team.

tip : The functions of GCD are all beginning with dispatch (Dispatch, Dispatch)

Queue:

dispatch_queue_t

serial Queue , the tasks in the queue are only executed sequentially

parallel queues , tasks in a queue are typically executed concurrently

Operation:

(1) Dispatch_async asynchronous operation, concurrent execution, unable to determine the order of execution of the task

(2) Dispatch_sync synchronous operation, sequential execution, can determine the order of execution of the task

5 , serial queue

For example:

-(void) viewdidload

{

[Super Viewdidload];

NSLog (@ "%@", [Nsthread CurrentThread]);

[Self gcdDemo1];

}

-(void) GcdDemo1

{

Put the action in the queue

In the C language function, the definition type, the vast majority of the end is _t or ref

asynchronous tasks that use serial queues are very, very useful! new child threads are overhead and cannot endlessly create new threads

That ensures efficiency (creating a new sub-thread), with the ability to implement concurrency

Application Case:

1> downloading pictures from the network

2> Filters (highlights, red-eye ...) )

dispatch_queue_t Q = dispatch_queue_create ("Cn.itcast.gcddemo", dispatch_queue_serial);

//[Nsthread CurrentThread] get current thread

for (int i = 0; i < ++i) {

Asynchronous task order execution, but if used in a serial queue, it will still be executed sequentially

Dispatch_Async(q, ^{

NSLog (@ "%@%d", [Nsthread currentthread],i);

});

}

Output Print Results:

The results are the same for each run:

If you change the asynchronous task order execution part of the code above into the following sequence of synchronization tasks:

for (int i = 0; i < ++i) {

Synchronous Task Order Execution

Dispatch_Sync(q, ^{

NSLog (@ "%@%d", [Nsthread CurrentThread], i);

});

}

The output prints the result as:

The sequential execution of the above synchronization tasks is almost impossible to use in actual development, but interviews may be asked.

6 , Parallel Queues

For example:

-(void) viewdidload

{

[Super Viewdidload];

NSLog (@ "%@", [Nsthread CurrentThread]);

[Self gcdDemo2];

}

-(void) GcdDemo2

{

  // Features: No formation, execution sequence programmer can not control!

Scenario: Concurrent execution tasks, no sequencing relationship

Parallel queues are prone to errors! Parallel queues do not control the number of new threads!

dispatch_queue_t q = dispatch_queue_create ("Cn.itcast.gcd2", dispatch_queue_concurrent);

for (int i = 0; i < ++i) {

Asynchronous task Order Execution

Dispatch_async (q, ^{

NSLog (@ "%@%d", [Nsthread CurrentThread], i);

});

}

}

Output Print Results:

The value of num for each run is different from the last number:

If you change the asynchronous task order execution part of the code above into the following sequence of synchronization tasks:

for (int i = 0; i < ++i) {

Synchronous Task Order Execution

Dispatch_sync (q, ^{

NSLog (@ "%@%d", [Nsthread CurrentThread], i);

});

}

The run output prints the result:

7 , Global queue

For example (as with parallel queue effects):

#pragma mark-Global queue (Apple provides a global queue for all apps to use in order to facilitate multi-threading design)

-(void) GcdDemo3

{

// the difference between a global queue and a parallel queue

//1> no need to create, direct GET You can use

//2> two queues perform the same effect

//3> the global queue does not have a name and the exact queue cannot be confirmed when debugging

// Remember: Always use in development Dispatch_queue_priority_default

Multi-threaded Priority reversal! A low-priority thread is blocking a high-priority thread!

dispatch_queue_t q =

Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);

for (int i = 0; i < ++i) {

Synchronous Task Order Execution

Dispatch_sync (q, ^{

NSLog (@ "%@%d", [Nsthread CurrentThread], i);

});

}

for (int i = 0; i < ++i) {

asynchronous tasks, which are executed concurrently, but are still executed sequentially if in the walkthrough queue

Dispatch_async (q, ^{

[Nsthread CurrentThread] can track the current thread in development

num = 1, which indicates the main thread

num = 2, which represents the 2nd child thread ...

NSLog (@ "%@%d", [Nsthread CurrentThread], i);

});

}

}

Run Print results:

8 , Home row (main thread queue)

For example:

-(void) GcdDemo4

{

Each application has only one main thread

Why do I need to work on the main thread?

// in the IOS in development, all UI update work must be performed on the main thread!

dispatch_queue_t q = dispatch_get_main_queue ();

The main thread is working, and unless the program is killed, the main thread's work will never end!

Opening a sync task causes the main thread to block

Dispatch_sync (q, ^{

NSLog (@ "Come here baby!");

// });

Asynchronous tasks that run on the main thread while maintaining formation

for (int i = 0; i < ++i) {

Dispatch_async (q, ^{

NSLog (@ "%@-%d", [Nsthread CurrentThread], i);

});

}

}

Run Output Print results:

9 , nesting in different queues Dispatch_sync the results

Global queues, which are executed on the main thread, do not deadlock

dispatch_queue_t q = dispatch_get_global_queue (dispatch_queue_priority_default, 0);

Parallel queues, which are executed on the main thread, do not deadlock

dispatch_queue_t q = dispatch_queue_create ("Cn.itcast.gcddemo", dispatch_queue_concurrent);

Serial queue, deadlock, but the code before the nested synchronization operation is executed

dispatch_queue_t q = dispatch_queue_create ("Cn.itcast.gcddemo", dispatch_queue_serial);

Direct deadlock

dispatch_queue_t q = Dispatch_get_main_queue ();

Dispatch_sync (q, ^{

NSLog (@ "Sync task%@", [Nsthread CurrentThread]);

Dispatch_sync (q, ^{

NSLog (@ "Sync task%@", [Nsthread CurrentThread]);

});

});

Ten , Dispatch_sync the application Scenario

Blocking the execution of a parallel queue requires that an operation be performed before subsequent operations, such as user logons, to ensure that local variables outside the block code are actually modified.

One , programming options

Serial Queue, Sync Task: No new threads required

serial queue, asynchronous task : Requires a child thread, thread creation and recycling does not require the programmer to participate! is one of the safest options.

Parallel queue, synchronous task: no thread creation required

Parallel queue, asynchronous task: How many tasks, open n threads Execute,

No matter what the queue and what tasks, the creation and recycling of threads does not require programmer involvement.

The creation of a thread is handled by the queue

"Concurrent" programming, in order to let programmers from the responsible line program control to free out! Only need to face queues and tasks

A , GCD Summary

GCD

(1) through GCD, developers no longer have to deal directly with threads, simply add code blocks to the queue to

(2) GCD manages a thread pool at the backend, and GCD not only determines which thread the code block will be executed on, but also manages those threads based on available system resources. This frees the developer from the work of thread management, easing the problem of a large number of threads being created through a centralized management thread

(3) With GCD, developers can think of work as a queue rather than a bunch of threads, a parallel abstract model that is easier to master and use

(4) in serial, nested synchronization in synchronization will cause blocking

GCD the queue

(1) GCD exposes 5 different queues: The primary queue running in the main thread, 3 different priority background queues, and a lower priority background queue (for I/O)

(2) Custom queues: serial and parallel queues. Custom queues are very powerful and are recommended for use in development. All blocks that are scheduled in the custom queue will eventually be placed in the system's global queue and in the thread pool

(3) When performing a task, first perform the first join task in the queue, then execute the second, third ...

(4) Tip: Do not recommend the use of different priority queues, because if poorly designed, there may be a priority reversal, that is, low-priority operations blocking high-priority operations

Comprehensive:

GCD's mission

1> Disptach_sync does not have the desire to create threads, it executes on the current thread

The main purpose is to block the execution of parallel queue tasks, and only after the current synchronization tasks have been executed can the subsequent tasks be executed

Application scenario: User login!

2> Dispatch_async has the desire to create threads, but how many threads to create depends on the type of queue

Queue of GCD

The 1> serial queue is similar to running, with only one runway and up to two

If there is an asynchronous task, the asynchronous task is executed in the new thread, and the synchronization task is still executing in the current thread

2> parallel queues resemble with the number of running, specific runways, which are determined by the system

GCD Queue :

Multi-Threading for iOS development

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.