ios--multithreaded Programming detailed parsing

Source: Internet
Author: User

Basic definition:
Program: An executable application generated by code. (e.g. Qq.app)
Process: A running program can be seen as a process. (for example, a running QQ is a process), and the process has all the resources needed to run it independently.
Threads: Code snippets that run independently in a program. (ex: 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 program really understand the execution unit, responsible for code execution.

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 when the program is started and is used to execute the main function.
A program that has only one main thread, called a single-threaded procedure.
The main thread is responsible for executing all code of the program (UI presentation and refresh, network requests, local storage, etc.). These codes can only be executed sequentially and cannot be executed concurrently.

Multithreading
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.
Several sub-threads can be opened as needed
Both the sub-thread and the main thread are independent units, and their execution does not affect each other, so they can execute concurrently.

single, multi-threaded differences
Single-threaded: Only one thread, code order execution, prone to code blocking (page suspended animation).
Multithreaded program: There are multiple threads, running independently between threads, can effectively avoid code blocking, and improve the performance of programs.
Note:
1. The addition and refresh of the UI in IOS must be done in the main thread.
2. IOS assigns 1M of stack space by default to the main thread, and allocates 512k space by default for sub-threads (the number of bytes allocated must be an integer multiple of 4k)
3. The allocated space is used to store the space in the thread that is open to variables, and is generally sufficient.
4. Unlike stack space usage, the main thread and child threads share the same block of heap space.
5. The child process must automatically release the pool.
Reason:
1. Freeing the pool frees up heap memory, although the heap area of the master thread is managed together, but the two are not involved. At the entrance of the program, the automatic free pool is set up by default, the main thread is responsible for executing the code, and the newly opened memory of the sub-thread is not within the main thread's jurisdiction, (the threads do not interfere with each other), so the space created by the child thread is not automatically freed, and manually write the release pool for the child
2. Writing @autoreleasepool Reason: The use of static methods in a short period of time to open up a large amount of memory space or recycling of convenient constructors, will cause memory instantaneous accumulation, program crash off.

2 types of multi-threading
Out-of-thread: After the thread finishes executing, it is not suspended. The thread ends and is destroyed.
Non-detached thread: Suspended after the thread has finished executing. Wait for wake up, do not destroy. The main thread must be non-detached thread
types of multithreading methods for IOS
1.NSObject
2.NSThread
3.NSOperationQueue
4.GCD

1. NSObject for asynchronous background execution
One of the simplest ways to perform in the background is stored in the nsobject.
Perform a method in the background
-(void) Performselectorinbackground: (SEL) Aselector withobject: (ID)

//withObject数字可以通过 calculate:的参数传到calculate方法中    [self performSelectorInBackground:@selector(calculate:) withObject:@"参数"];// isMainThread 是NSThread 的类方法, 返回值BOOL ,判断是不是主线程// 主线程中 输出 1 NSLog(@"main ======%d",[NSThread isMainThread]);
//子线程中输出 0.    NSLog(@"isMainThread = %d",[NSThread isMainThread]);

2.NSThread is a lightweight, multi-thread

//    方式一 需要开启 (实际可以创建多个NSThread)    NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(calculate:) object:nil];// 手动开启 [thread1 start];// 取消 (一般不需要取消) [thread1 cancel];// 方式二 不需要手动开启 [NSThread detachNewThreadSelector:@selector(calculate:) toTarget:self withObject:nil];
    NSLog(@"isMainThread = %d",[NSThread isMainThread]);

3.NSOperation
Defined:
Class 1.NSOperation, which belongs to M in MVC, is an abstract class used to encapsulate the code and data associated with a single task
2. Because it is abstract and cannot be used directly, the subclass (Nsinvocationoperation or nsblockoperation) is used to accomplish the actual task.
3.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 is a subclass of Nsinvocation that encapsulates the target that performs the operation and the action to execute.

//    方式一:NSInvocationOperationNSInvocationOperation * invocation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(calculate:) object:nil];// 手动开启 [invocation start]; 此时在 calculate:方法中输出,输出结果为1,原因:calculate方法只是封装了主线程任务的一部分,仍然是主线程。 NSLog(@"isMainThread = %d",[NSThread isMainThread])

Nsblockoperation is a subclass of Nsoperation that encapsulates the code blocks that need to be executed

//    方式二:NSBlockOperation ,这种方式同上仍然只是封装的任务,并没有实现多线程。//避免block 的请引用问题,所以使用__weak.    __weak typeof (self) temp = self;    NSBlockOperation * block = [NSBlockOperation blockOperationWithBlock:^{ [temp calculate]; }]; [block start];

implementing multi-threaded two child threads concurrently with Nsoperationqueue
Note: At this point the two start needs to be commented out, so that the real implementation of multithreading

//can be Nsoperationque    UE creates pairs of columns, adds operations to the queue, and completes multitasking simultaneously. Nsoperationqueue * queue = [[Nsoperationqueue alloc] Init]; #warning Note: Be sure to set the concurrency number ahead of time, when the maximum concurrency is 1, and become serial [queue Setmaxconcurrentoperationcount:2]; [queue addoperation:invocation]; [queue Addoperation:block]; //add Operation NSLog (@ "Operationcount =%lu", queue.operationcount); NSLog (@ "operations =%@", queue.operations);    

Attention:
(1) Nsoperationqueue is the operation queue, which is used to manage the execution of a set of Operation objects, automatically opens up a number of threads for operation as needed, and the concurrent execution of the completed tasks
(2) Where nsoperation can adjust his priority in the queue
(3) Thread synchronization is implemented when the maximum concurrent number is set to 1.

4.GCD (Grand central Dispatch)
GCD Introduction: Grand Central Dispatch abbreviation GCD. To optimize applications that support multi-core processors and other symmetric multi-processing systems.
GCD is a function-level multi-threading, with higher performance and more powerful functions

GCD Core Concepts
Task: A section of code with a certain function, usually a block or function
Distribution queue: GCD works as a queue, FIFO. But not the order of entry we set. is the order in which the system executes.
GCD or, depending on the type of distribution queue, create an appropriate number of threads to execute the tasks in the queue.

two types of queues in GCD
The dispatch queue is divided into the following two types
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 and the serial queue are executed concurrently. Serialqueue can implement thread synchronization.
2.Concurrent: Multiple tasks can be performed concurrently, but in accordance with FIFO

GCD function *

//1. 主队列 :串行队列,并且执行的是主队列中任务//2. 全局队列 :并行对列//3. 自定义队列{串行队列,并行队列}//   串行与并行没有关系//  主队列与全局队列都是单例, 主队列串行,全局队列并行。 都是直接获   取,直接使用,不需要创建,也就是一直存在。

Get the Home row

Dispatch distribution, dispatch equivalent to int a = 10;dispatch_queue_t mainqueue = Dispatch_get_main_queue ();#pragma mark adds a task to the main queue, the task is queued for execution, verifying that the home row is a serial queueDispatch_async (Mainqueue, ^{NSLog (@"First task"); });Dispatch_async (Mainqueue, ^{NSLog (@ "second Mission"); });  #pragma mark delay, add a task to the queue, the task will not only queue, but also at a delayed point in time to execute # Warning has a code block Sinppet #warning it is best not to add a delay to the main queue (also do not add a delay in the serial queue, the time is not up to the program hangs, the latter cannot be executed) //10 seconds. Time is not always accurate, the program will also take time to run //first defines the time period * nsec_per_sec, which represents 10 seconds dispatch_time_t times = Dispatch_time ( Dispatch_time_now, (int64_t) (10 * nsec_per_sec)); Dispatch_after (Time, Mainqueue, ^{nslog (@ "fourth task, executed after 10 seconds");});  #pragma repeats n times the parameter T indicates the execution of the number of times. Dispatch_apply (3, Globequeue, ^ (size_t t) {NSLog (@ "important thing to say three times"); nslog (@ "%zi", t);});       

Get Global Queue

  #pragma mark 2. Global queue: The parallel queue execution method first comes first service. Parallel: Time slice rotation dispatch_queue_t globequeue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0);#pragma add a task to the queue and add a grouping tag//create Group Group dispatch_group_t group = Dispatch_group_create () ; //Add Task Dispatch_group_async (group, GlobeQueue, ^{NSLog ( Span class= "hljs-string" >@ "first Group first squad"); }); Dispatch_group_async (group, Globequeue, ^{NSLog (@ "first group second squad" ); }); Dispatch_group_async (group, Globequeue, ^{NSLog (@ "first group third squad" ); }); #pragma Mark adds a task to the queue, and when all the tasks of a group are executed, This task will not be executed (this statement is not necessarily correct by practice) #warning Note: This method is related to the location of the queue being added. When it is at the end of the queue, it is executed last. The result is not necessarily at the front of the currently grouped queue. Dispatch_group_notify (group, Globequeue, ^{NSLog (@ "You do it first, I'm not in a hurry "); });

Custom Queues
First parameter: Queue identifier, which can get an identifier for a queue
Second parameter: type of queue, (serial or parallel)

Custom Serial Queue

#warning Note: The first argument is a string in C, not a character object in OC. It's actually C code, so it doesn't appear.dispatch_queue_t serialqueue = dispatch_queue_create ("Serial", dispatch_queue_serial);  Add Task Dispatch_async (serialqueue, ^{ NSLog (@"first task");}); Dispatch_async (serialqueue, ^{ NSLog (@"second task");}); Dispatch_async (serialqueue, ^{ NSLog (@"Third task");}); //Output S is serial const Char *s = Dispatch_queue_get_label (serialqueue); NSLog (@"%s", s);                

Custom parallel queues

    dispatch_queue_t concurrentQueue = dispatch_queue_create("current", DISPATCH_QUEUE_CONCURRENT);    dispatch_async(concurrentQueue, ^{        NSLog(@"1"); });

Dispatch_barrier_async ()

#pragma mark 将此函数添加到队列的任务,需要等其执行完成后才可以执行其他队列任务#warning 前提:必须是自己定义的并行队列,使用系统提供的不可以。// 自定义并行队列 dispatch_queue_t concurrentQueue2 = dispatch_queue_create("current2", DISPATCH_QUEUE_CONCURRENT);// 必须等待barrier 函数执行完成, 余下的队列任务才可以执行 dispatch_barrier_async(concurrentQueue2, ^{ int sum = 0; for (int i = 0; i < 63555000; i++) { sum += i; } NSLog(@"执行完成"); });

Dispatch_sync ()

#pragma mark 必须等待sync 里面的block 代码执行完成,余下的队列中函数才可以执行 dispatch_sync    dispatch_sync(concurrentQueue2, ^{        int sum = 0;        for (int i = 0; i < 63555000; i++) { sum += i; } NSLog(@"都等着我。。。。。。。。。。。。"); });

Dispatch_async_f ()

#pragma mark 将任务添加到队列中,任务是函数非 block//    GCD 可以使用此函数,向队列中添加函数,让函数执行。//    函数类型 void (*)(void *).无返回值有参数,但是参数类型是void例如:void function(void *name){ NSLog(@"%s",name);}// 第二个参数:函数参数的内容。// 第三个参数: 函数名字。 dispatch_async_f(concurrentQueue2, "string", function);

Dispatch_once ()

#pragma mark 任务添加到队列中,但是任务在程序运行过程中,只执行一次 有代码快。//    经验证得非常顽强 ,即使是在循环中也是只执行一次。    static dispatch_once_t onceToken;    for (int i = 0; i < 5 ; i++) { dispatch_once(&onceToken, ^{ NSLog(@"单例"); }); } dispatch_once(&onceToken, ^{ NSLog(@"单例2"); });}

Attention:
Only the home column is name = Main, other name = NULL
Only the home column is number = 1, other than the 1.number order is the order of internal execution, not the order of addition. Number is the same value in serial queue

Main threadDispatch_async (Dispatch_get_main_queue (), ^{NSLog (@"Currentthreadmain =%@", [Nsthread CurrentThread]);NSLog (@"Main%d", [Nsthread Ismainthread]); });Global queueDispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{NSLog (@"Globel =%@", [Nsthread CurrentThread]);NSLog (@"Globel =%d", [Nsthread Ismainthread]); });Paralleldispatch_queue_t Concurrentqueue = Dispatch_queue_create ("Concurrent", dispatch_queue_concurrent);Dispatch_async (Concurrentqueue, ^{NSLog (@"Concurrentqueue =%@", [nsthread CurrentThread]); NSLog (@"Concurrentqueue =%d", [nsthread ismainthread]);}); //serial dispatch_queue_t serialqueue = dispatch_queue_create ("Serial", dispatch_queue_serial); Dispatch_async (serialqueue, ^{ NSLog (@"Serialqueue 1 =%@", [nsthread CurrentThread]); Dispatch_async (serialqueue, ^{ NSLog (@"serialQueue2 =%@", [nsthread CurrentThread]);}); //Output result:                


Summarize:
1. There are many ways to implement the GCD function, although chaotic but regular
Dispatch_async () Add in queue
Dispatch_after () queue Add, deferred execution
Dispatch_apply () queue to add, repeat execution
Dispatch_group_async () first creates a group, adds the task to the queue, and marks the grouping
Dispatch_group_notify () When you add a task to a queue, the task is not executed until all the tasks for that group have been executed.
Dispatch_barrier_async (), this task executes while other tasks wait. Multithreading that you must create yourself
Dispatch_sync (), block does not execute, the following code does not execute. Similar function
Dispatch_once () executes only once, Singleton
Dispatch_async_f () can add a task as a function instead of a block, which means the function can be used as a function parameter
2. Dispatch_once (), Dispatch_after () have code blocks.

ios--multithreaded Programming detailed parsing

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.