iOS interview - Multithreading

Computer multi-process development background:

Early computer work program is single-batch process, speaking written job cards turn into the batch computer program execution, efficiency is very low, followed by the emergence of multi-channel batch program, with a period of time to allow colleagues to quickly perform multiple programs Although very efficient, but later with the follow-up of hardware technology, in addition to time-sharing system that is processing jobs it has become a process of work; according to the time each process of fragmentation, the same time to quickly switch execution. Later appeared real-time system more efficient. . .

Multithreading concept:

Multithreading refers to the concurrent execution of multiple threads technology can be implemented in software or hardware. A computer with multi-threading capability for supporting hardware can execute multiple threads at the same time, thereby increasing processing power of computers.

Multi-threaded relationship to the process:

The process is the basic unit of program execution, and the thread is the basic unit of program execution, a process can have multiple threads, and has at least one thread, each thread is an independent execution, multiple threads can share its code to process the data, process space and the corresponding heap space;

Multi-threaded program developed to bring convenience:

  1. Single-threaded in the face of time-consuming operation will block the UI thread, the user interface of mouse clicks, scrolling gesture will be executed immediately, resulting in a very good user experience, multi-threading technology allows consuming operations into a separate thread in the execution area, so as not to affect the interaction of the UI thread, improve user experience;
  2. Relatively speaking process, multi-threaded create, required for switching cpu consumption, memory footprint will be small;
  3. For multi-core operating system, multi-core resource can not be a good use of a single thread, a waste of resources.

The introduction of multi-threading issues:

  1. Multi-threaded code will be more complicated, difficult, difficult to maintain them;
  2. For the model of shared data to be shared by multiple threads, problems may arise thread deadlock;
  3. As the thread creation, scheduling, handover will consume some cpu computing resources, memory resources, instruction scheduling resources, crazy create multiple threads will be counterproductive consequences;
  4. Unsafe data, for the same shared data area, can be manipulated;

iOS development process, multithreading programs:

C language based POSIX threads, the thread becomes pthread; multithreaded operating system implementations, can be achieved since oc c may also be used mixed, posix threads may be used in the development of iOS; posix threads advantage is a more level performance will be efficient, but due to the c language development, so we need to manually manage the content of the thread, for the development of efficiency is a disadvantage;

nsthread thread package on c language, object-oriented multi-threaded implementation, API as follows:

1.  init 方法实现多线程创建,该方法需要我们手动执行strart指令,将它放进带线程就绪队列,等待系统自己出发;
2. detachNewThreadSelector 方法创建并自动放到线程就绪队列等待系统自动去出发;

2.1, nsthread advantages:

1. nsthread提供适合oc开发人员使用多线程实现api,降低开发门槛;
2. nsthread 提供了一套工具酷,我们可以快捷拿到多线程的信息和状态,例如: 是否是主线程、是否被取消,是否正在运行等

2.2, nsthread shortcomings

1. nsthread 的最大缺点是线程之间的通信比较麻烦,也是设计的一种缺陷;

GCD

  1. concept

gcd we call central dispatch management, based on the c interface is apple company in order to take full advantage of multi-core resource can not thread the introduction of a multi-threaded implementation; it is a workflow event into several smaller tasks into serial or concurrent execution queue , was added to the FIFO rule-thread execution units, and then execution thereof is synchronous or asynchronous;
1.1: advantages:

高效: 基于mach内核线程调度;
线程安全:不用开发者关心线程的内存问题;
使用简单,少代码解决大问题;
  1. The core mechanism - Queue

gcd is the core of the queue
gcd queue into: serial, concurrent, main queue, global queue, the queue group

  1. Serial / Concurrent / Synchronous Asynchronous combination corresponding to the result
 1. 主线程的时间优先
 2. 串行同步执行: 执行完一个任务,再执行下一个任务。不开启新线程,都在主线程执行。
 3. 串行异步执行: 开启新线程,但因为任务是串行的,所以还是按顺序执行任务。
 4. 并发队列异步执行: 并发执行,会开启新的线程。
 5. 并发队列同步执行; 按顺序执行,不会开启新的线程。
 6. 主队列同步事件: 
 7. 主队列异步事件:  按次序执行。
  1. gcd special function:
    4.1 boom function dispatch_barrier_ (a) sync

When we need to perform the asynchronous event synchronization function dispatch_barrier_sync we need
to perform asynchronous dispatch_barrier_async

4.2 semaphore

dispatch_semaphore share resources in order to solve the competition problem, you can use a semaphore to determine whether the resource can be accessed.
dispatch_semphore_create create a semaphore, a thread parameter is the largest co-workers can access;
dispatch_semphore_waite to perform semaphore operations minus 1, if the result is greater than 0, the resource can be accessed directly;
dispatch_semphone_sign signal plus a variable to perform operations necessary to access the complete release occupancy rights to resources, namely semaphores plus 1, does not affect other threads to access.

4.3 deferred execution function

dispatch_after_t function parameters: dispatch_time_t dispatch_queue_t block

4.4 set of variables
when we needed after multiple requests to enter the next step, we need the following function \

dispatch_group_t

1. 创建一个全局的队列,默认优先级
2. 创建一个group_t 
3. 创建group任务加入到全局队列
4. 监听组队列完成的notify dispatch_group_notify

// 加载图片例子:
   NSLog(@"全部开始-----%@", [NSThread currentThread]);
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_async(group, queue, ^{
        sleep(4);
        NSLog(@"子线程1-----%@", [NSThread currentThread]);
    });
    
    dispatch_group_async(group, queue, ^{
        sleep(3);
        NSLog(@"子线程2-----%@", [NSThread currentThread]);
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部结束-----%@", [NSThread currentThread]);
    });

4.5 dispatch_group_enter/dispatch_group_leave 函数

4.4 The task group is just a simple task forces in the output word, if an asynchronous request to join in it lies a problem:

The code in question:

NSLog(@"全部开始-----%@", [NSThread currentThread]);
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.example.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_group_async(group, queue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(4);
            NSLog(@"模拟请求1-----%@", [NSThread currentThread]);
        });
    });
    
    dispatch_group_async(group, queue, ^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(3);
            NSLog(@"模拟请求2-----%@", [NSThread currentThread]);
        });
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部结束-----%@", [NSThread currentThread]);
    });

It prints log: all start - all over - Task 2, Task 1, we find that this is the case with our requirements is not the same, we ask that all tasks are executed before the end of the function notify it in advance to perform it.

In order to solve the above problems need to use dispatch_group_enter / dispatch_group_leave
before the set of tasks within the group, each operate asynchronously, execute dispatch_group_enter function parameters are variable group; dispatch_group_leave executed when the task is completed inside ()
code is as follows:

NSLog(@"全部开始-----%@", [NSThread currentThread]);
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.example.gcdDemo", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_group_async(group, queue, ^{
        dispatch_group_enter(group);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(4);
            NSLog(@"模拟请求1-----%@", [NSThread currentThread]);
            dispatch_group_leave(group);
        });
    });
    
    dispatch_group_async(group, queue, ^{
        dispatch_group_enter(group);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(3);
            NSLog(@"模拟请求2-----%@", [NSThread currentThread]);
            dispatch_group_leave(group);
        });
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"全部结束-----%@", [NSThread currentThread]);
    });

4.6 dispatch_apply fast Su iterated function parameters: the number of iterations, where the queue, the task

4.7 dispatch_once: the task is executed only once, usually in a single case,

FAQ 5.gcd of
5.1 thread deadlock
reasons: Queue cause - Scene: executed in the main thread synchronization add tasks to master queue
will block (perform a log) to add to join us in synchronous execution method viewdidload wish: Example queue, this easy-to-back with a final log, run discovery, block log, the log ends are not printing, explained by the phenomenon is too late to block the implementation of the end of the log can not be executed. The reason is, first, the program will first perform the synchronization function is added to the thread execution unit, and then perform the synchronization function in accordance with the requirements will be added to block the implementation of the main queue, because it is synchronous function, can only wait until the end of the block, the synchronization function to return, and the block in the main queue, it is only a mechanism for a queue of tasks to complete before it can out of the queue, so that the synchronization function can not return led to the end can not be printed in the order, block can not be executed, cause a synchronization function can not return, the system can not enter the next step , it is wrong - deadlock.

Guess you like

Origin blog.csdn.net/weixin_33782386/article/details/90922048