iOS multithreaded programming

Source: Internet
Author: User

iOS multithreaded programming

1. Processes, threads, tasks

Process: When a program runs, it assigns a process to manage some of his resources.

Threads: One or more execution units contained within a process are called threads, and threads generally do not hold resources, but can use the resources of the process in which they reside.

Task: What to do in a process or thread.

In the operating system that introduces threading, the process is usually used as the basic unit of allocating resources, and the thread as the basic unit of independent operation and independent Dispatch.

The thread is smaller than the process and has less overhead for scheduling, which can improve the concurrency of multiple tasks within the system.

A program has at least one process, and a process has at least one thread. A program is a process, and multiple tasks in a program are called threads.

A thread can only belong to a process and it can only access resources owned by that process. When the operating system creates a process, the process automatically requests a thread that is called the main thread or the first. An application (application) is made up of one or more collaborative processes.

The meaning of multithreading is that in an application, there are multiple execution parts that can be executed concurrently. Provides a coordination mechanism to prevent conflicts between processes and threads, and to allow resources to be shared between processes and threads on the other.

2. iOS multithreaded Programming technology

There are three kinds (actually four kinds, and pthreads,c language framework)

> Nsthread

> nsoperation

> GCD (Grand Central Dispatch)

From top to bottom, the package degree from low to high, the higher the package, the simpler the use is also the official recommended use.

Three ways to compare:

Nsthread: Compared to the other two is relatively lightweight. This method is officially encapsulated, is completely object-oriented, so you can directly manipulate the thread object, very intuitive and convenient. However, it is necessary to manage the thread's lifecycle, thread synchronization, and thread synchronization to lock up the data with some overhead. Use is relatively simple, but not smart enough to use in some simple scenarios.

Nsoperation: Fully object-oriented. The main related classes are nsoperation (Task) and Nsoperationqueue (Task queue), where Nsoperationqueue is implemented with GCD after IOS4 introduces GCD. In this way, you do not need to care about thread management, data synchronization operations. Hides a lot of complex code and provides a simple API.

GCD: It is the solution that Apple proposes for multi-core parallel operation, it will automatically utilize more CPU cores (such as dual-core, quad-core) rationally. This approach also automatically manages the thread's life cycle (creating threads, scheduling tasks, destroying threads), without having to manage them, just to tell them what to do. Although the use of C language, but because the use of block, the use is also very convenient, flexible. There is also the concept of "task", "queue" in GCD.

First, Nsthread ===========================================

1. Create and manage threads using Nsthread

> Creating Threads

mode One : Instance method

[Nsthread alloc] InitWithTarget:selector:object:]

Parameter one: The recipient of the thread operation message Self

Parameter two: Selector method, thread operation method, this method can only take one parameter, and cannot have return value

Parameter three: parameters of the thread manipulation method

Threads created using this method do not start automatically and need to invoke the threading method:

[Thread start]//start start and execute thread

Mode Two: class method

[Nsthread DetachNewThreadSelector:toTarget:withObject:]

Parameters above the same name;

Threads created by this method automatically start execution without having to be manually turned on.

> Threading Methods

Cancel Thread

-(void) cancel;

Start thread

-(void) start;

Set/Get state of a thread

@property (readonly, getter=isexecuting) BOOL executing;

@property (readonly, getter=isfinished) BOOL finished;

@property (readonly, getter=iscancelled) BOOL cancelled;

Set and get the thread name

-(void) SetName: (NSString *) n;

-(NSString *) name;

Gets the current thread

+ (Nsthread *) CurrentThread;

Get the main thread

+ (Nsthread *) Mainthread;

Pauses the current thread for a period of time, or pauses to a moment

+ (void) Sleepfortimeinterval: (nstimeinterval) time;

+ (void) Sleepuntildate: (NSDate *) date;

Set Thread Priority

+ (BOOL) SetThreadPriority: (double) p;

> Inter-thread Communication

The UI must never be accessed on a non-main thread, and should be updated on the main thread

[Self Performselectoronmainthread: @selector (updateUI:) Withobject:data Waituntildone:yes];

Data communication between threads and threads

[Self performselector: @selector (senddata:) onthread:thread2 withobject:obj Waituntildone:yes]

> Thread Synchronization

When multiple threads access the same shared resource, in order to ensure the accuracy of the data resources, it is necessary to lock the resources, that is, only one thread accesses the shared resource at a time, and the other threads wait in the queue.

Nslock Lock

[[Nslock alloc] init]

[Thelock Lock];

..... shared resources to access

[Thelock unlock];

Second, nsoperation========================================================

1. Nsoperation

This class is an abstract class that cannot be used directly.

You can only use system-defined subclasses or custom inheritance nsoperation.

Well-defined subclasses: Nsinvocationoperation and Nsblockoperation

A Nsoperation object corresponds to a task/thread that needs to be placed in the Nsoperationqueue task queue/pool before the task/thread is started and executed.

2. Nsinvocationoperation

Action execution of a task is performed in a method

> [[nsinvocationoperation alloc] initwithtarget:self selector: @selector (..) Object:nil]

3. Nsblockoperation

The operation of the task is performed in the block

> [Nsblockoperation blockoperationwithblock:^{

...

}]

4. Nsoperationqueue add a task to the task queue to start the execution

> Nsoperationqueue *que = [[[Nsoperationqueue alloc] init]//Custom queue

> que.name//queue name

> Que.maxconcurrentoperationcount//MAX task concurrency, set to 1 to perform the task serially. The default is-1, which means that the tasks in the queue are executed at the same time without a limit.

> [que addoperation:oper1]//Add task to queue to start execution

In addition to custom queues:

Primary queue (the tasks in this queue are performed on the main thread): [Nsoperationqueue Mainqueue]

Current queue: [Nsoperationqueue Currentqueue]

5. Dependencies between tasks

[Oper1 Adddependency:oper2]//Task 1 depends on Task 2, Task 1 execution must wait for Task 2 to finish before starting

Note This must be done before the task is added to the queue!!!

6. The sdwebimage picture download principle uses the Nsoperation,nsoperationqueue

Third, gcd============================================================

1. GCD: Tasks, queues

Queues are divided into serial, parallel queues.

Task execution in serial queue: GCD will take out a task in FIFO (first-in, FIFO), execute one, then fetch the next, and so on.

Task execution in a parallel queue: GCD is also the FIFO to remove the task, and the serial difference is: After the removal of the task will be placed on another thread, and then take out one put to another thread .... Because the process of taking a task is quick, it seems that all tasks are executed together. Note: GCD will control the number of concurrent tasks based on system resources, too many tasks, and will not allow all tasks to execute concurrently.

2. Sorting from the program queue:

Main queue: (serial queue) dispatch_queue_t QM = Dispatch_get_main_queue ();

Custom queues: (Serializable, parallel) dispatch_queue_t qself = dispatch_queue_create ("Myqueue", dispatch_queue_concurrent); Specifies whether the queue is serial dispatch_queue_serial or parallel through the second parameter dispatch_queue_concurrent

Global parallel queue: dispatch_queue_t QG = dispatch_get_global_queue (dispatch_queue_priority_default, 0);

3. Add the task to be performed in the queue (synchronous [blocking current thread], asynchronous task [does not block current thread])

Dispatch_async (QM, ^{

Tasks to perform in the specified queue ...

});

4. Queue groups

Multiple queues can be placed in a group.

Create a queue group

dispatch_group_t group = Dispatch_group_create ();

Dispatch_group_async (group, queue, ^{

In the queue group that you specify, add queue queues, and add tasks in the queue ...

});

Dispatch_group_notify (group, queue, ^{

After all tasks in the specified group are complete, send a notification to the specified queue and perform a task ..., which is typically used to update the UI in the main queue

});

iOS multithreaded programming

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.