ios-senior10-Multithreading (Child thread creation)

Source: Internet
Author: User

1. Multithreading Overview

Program: The executable application generated by the source code. (Eg:QQ.app)

Process: A running program can be seen as a process. (eg: a running QQ is a process), and the process uses all the resources needed to run it independently.

Threads: Code snippets that run independently in a program. (eg: code to receive QQ messages)

A process is made up of one or more threads. The process is only responsible for the scheduling and allocation of resources, the thread is the real execution unit of the program, responsible for code execution.

1.1 Single Thread

Each running program (that is, a process) contains at least one thread, which is called the main thread.

The main thread is created at program startup and is used to execute the main function.

A program that has only one main thread, called a single threaded procedure.

In a single-threaded program, the main thread is responsible for executing all of the program's Code (UI presentation and refresh, network requests, local storage, and so on). These codes can only be executed sequentially and cannot be executed concurrently.

1.2 Multi-Threading

A program that has multiple threads, called a multithreaded program.

iOS allows users to carve out new threads themselves, which are called child threads, as opposed to the main thread.

You can open up several sub-threads as needed.

Both the sub-thread and the main thread are separate running units that are independent of each other and can be executed concurrently.

1.3 Differences between single-threaded and multithreaded

Single-threaded: Only one thread, the main thread, code order execution, prone to code blocking (the page suspended animation).

Multi-Thread Program: There are multiple threads, running independently between threads, can effectively avoid code blocking, and improve the performance of programs.

Note: the addition and refresh of the UI in iOS must be done in the main thread.

Multithreading under the 2.iOS platform

2.1NSThread

Method:

Initializes a child thread, but needs to be opened manually

-(ID) initwithtarget : (ID) Target selector: (SEL) Selector Object:(ID) argument

Initializes a sub-thread and automatically opens

+ (void) detachnewthreadselector : (SEL) Aselector totarget: (ID) atarget Withobject:(ID) anargument

Turn on child threads

Start [Operation start]

Cancels the current child thread

Cancel [Operation Cancel]

Source:

Manually open sub-threads

Nsthread *Thread = [[Nsthread alloc] initwithtarget:self selector: @selector (sayhi) Object:nil];

[Thread start];

Using Nsthread and NSObject to implement the thread, the system will be automatically released, not off the line

[Thread cancel]; Instead of actually canceling, it sends a signal to the thread, which is canceled by this signal.

[Thread exit]; Exit the thread directly

Automatically turn on child threads

[Nsthread detachnewthreadselector: @selector (sayhi) totarget:self Withobject:nil];

Self.view.backgroundColor = [Uicolor Redcolor];

2.2NSObject

Using Performselectorinbackground to open sub-threads

[Self performselectorinbackground : @selector (sayhi) withobject:@ "test"];

In the method called by the child thread, return to the main thread, calling another method

[Self performselectoraonmainthread: @selector (Mainthreadchangecolor) Withobject:nil Waituntildone:yes];

-(void) Mainthreadchangecolor {

Self.view.backgroudColor = [Uicolor Magentacolor];

}

Method:

Get current thread: [Nsthread CurrentThread]

Get main thread: [Nsthread Mainthread]

Thread hibernation 2 seconds: [Nsthread Sleepfortimeinterval:2]

Attention:

1. Each thread maintains this corresponding NSAutoreleasePool object and puts it on the top of the stacks on-line. When the thread ends, the auto-free pool is emptied.

2. In order to ensure the timely release of objects, in the multi-threaded method you need to add an automatic release pool.

3. When the application opens, an auto-free pool is automatically created for the main thread.

4. We manually create a sub-thread that requires us to manually add an auto-release pool.

4.NSOperation and Nsoperationqueue

The Nsoperation class, which belongs to M in NVC, is an abstract class used to encapsulate the code and data associated with a single task.

Because it is abstract and cannot be used directly, the subclass (Nsinvocation,nsblockoperation) is used to perform the actual task.

Nsoperation (with subclasses), just an operation that itself has no main thread, sub-thread, and can be used in any thread. Usually used in conjunction with Nsoperationqueue.

Nsinvocationoperation: Encapsulates the target that performs the action and the action to be executed

Nsblockoperation: Encapsulates the code that needs to be executed

Nsoperation can not directly create multi-threaded, need to rely on: nsoperationqueue

When you use the subclass of Nsoperation to create a thread, be sure to start the line;

When using a subclass of nsoperation to create a thread, the thread is actually not created in real sense.

SOURCE program:

nsinvocationoperation *operation = [[Nsinvocationoperation alloc]initwithtarget: Self selector:@ Selector (test) Object:nil];

nsblockoperation *blockoperation = [nsblockoperation blockoperationwithblock: ^{

NSLog (@ "I am block");

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

NSLog (@ "*******%@", [Nsthread mainthread]);

}];

-(void) test {

NSLog (@ "?");

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

NSLog (@ "Mainthread = =%@", [Nsthread Mainthread]);

}

Create a child thread with a queue

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

[Queue addoperation: operation];

[Queue addoperation: blockoperation]; //When there is a addoperation, it is not possible to use start or it will cause a crash.

-(void)Touchesbegan:(nsset<uitouch *> *) touches withevent: (Uievent *) Event {

Create a Queue object

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

Maximum number of concurrent values

When the value is set to 1, it can be called serial (single-threaded) sequential execution

Queue.maxconcurrentoperationcount = 2;

When the value setting is greater than 1, it is called parallel: multiple channels perform their respective tasks simultaneously

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

Create 10 threads

Nsblockoperation *blockoperation = [Nsblockoperation blockoperationwithblock:^{

NSLog (@ "CurrentThread = =%@,mainthread = =%@,%d", [Nsthread currentthread],[nsthread mainthread],i);

}];

[Queue addoperation:blockoperation];

}

}

5.GCD (Grand Central Dispatch) uses

Summary: GCD is a multi-core programming technology developed by Apple. Primarily used to optimize applications to support multicore processors and other symmetric multi-processing systems.

GCD provides functions for multithreaded development, higher performance and more powerful functions.

It is also available for first release on Mac OS X 10.6,ios4 and above.

Task: A code snippet that has some functionality. is usually a block or function.

Distribution queue: GCD work in a queue, FIFO

GCD creates the appropriate number of threads to perform the tasks in the queue, based on the type of distribution queue.

Two types of queues in GCD:

1.SerialQueue: perform only one task at a time. Serial queues are typically used to synchronize access to specific resources or data. When you create multiple serial queues, they are executed synchronously, but the serial queue is executed concurrently with the serial queue.

2 . Concurrent: Multiple tasks can be performed concurrently, but in accordance with FIFO

#pragma mark-use GCD to create a serial queue

First: System-provided methods for creating a serial queue

dispatch_queue_t queue = Dispatch_get_main_queue ();

In real development If you need to create a serial queue, it is more customary to use this

The second kind: to create yourself

dispatch_queue_t = Dispatch_queue_create (dispatch_queue_serial,0);

#pragma mark-use GCD to create a parallel queue

The first kind: the way of the system

Parameter 1: Priority (with 4, no obvious difference)

dispatch_queue_t queue = Dispatch_get_globel_queue (dispatch_queue_priority);

The second type: the way you define yourself (parameters are not the same as serial)

Parameter 1: Indicates the name of the Create queue

Parameter 2: System-provided macros

Create a queue

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

Create a task

Dispatch_async (queue,^{

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

NSLog (@ "main = =%@", [Nsthread Mainthread]);

NSLog (@ "I am task one, sub process one");

});

Dispatch_async (queue,^{

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

NSLog (@ "main = =%@", [Nsthread Mainthread]);

NSLog (@ "I am task two, sub-process two");

});

Dispatch_async (queue,^{

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

NSLog (@ "main = =%@", [Nsthread Mainthread]);

NSLog (@ "I am task three, sub-process three");

});

#pragma mark--a few seconds to do everything.

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{

NSLog (@ "3 seconds");

}

);

#pragma mark-repeatedly add multiple tasks to a queue

dispatch_queue_t queue = Dispatch_queue_create (0,dispath_queue_concurrent);

Dispatch_apply (100,queue,^ (size_t index)) {

NSLog (@ "index =%zu", index);

}

#pragma mark-Group

Create a group

dispatch_group_t group = Dispatch_group_create ();

Create a parallel queue

dispatch_queue_t queue = Dispatch_queue_create (0,dispatch_queue_concurrent);

Create a Task 1

Dispatch_group_asunc (group,queue,^{

NSLog (@ "I am task 1");

});

Create a Task 2

Dispatch_group_asunc (group,queue,^{

NSLog (@ "I am Task 2");

});

Create a Task 3

Dispatch_group_asunc (group,queue,^{

NSLog (@ "I am task 3");

});

Used to listen for all tasks, so this function code must be written after all tasks

Dispatch_group_notify (group,queue,^{

NSLog (@ "I am the listener, the last Execution");

});

#pragma mark-Serial in concurrency (Wolf in sheep's clothing)

Create a serial queue

dispatch_queue_t queue = Dispatch_queue_create (0,dispath_queue_concurrent);

Dispatch_async (queue,^{

NSLog (@ "Task 1");

});

Dispatch_async (queue,^{

NSLog (@ "Task 2");

});

Dispatch_async (queue,^{

NSLog (@ "Task 3");

});

#pragma mark-loaddata

1.url

Nsurl *url = [Nsurl urlwithstring:@ "http://www.baidu.com"];

2.session

Nsurlsession *session = [Nsurlsession sharedsession];

3.task

Nsurlsessiondatatask *task = [Session Datataskwithurl:url completionhandler:^ (NSData *_nullabel data,NSURLResponse *_ Nullabel response,nserror *_nullable error) {

if (Error = = Nil) {

Working with Data

Back to main thread refresh UI

Dispatch_async (Dispatch_get_main_queue (), ^{

Your own flexibility to write something!!!

})

}

}];



ios-senior10-Multithreading (Child thread creation)

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.