iOS multi-Threading--deep parsing

Source: Internet
Author: User
Tags gcd posix semaphore

Multithreading in your project why multithreading with GCD instead of nsoperation? Have you ever found out that the foreign Daniel is using nsoperation for their multithreading? Can you tell me the reason why they did it?

Relationship:

①: First understand the relationship between the two, nsopertaionqueue with GCD build encapsulated, is gcd high-level abstraction!

②:GCD only supports FIFO queues, while queues in Nsoperationqueue can be prioritized to perform order adjustments for different operations. GCD does not support dependency settings between asynchronous operations. If an operation relies on data from another operation (the producer-consumer model is one of them), use Nsoperationqueue to perform the operation in the correct order. GCD does not have built-in dependency support.

③:nsoperationqueue supports KVO, which means that we can observe the execution state of a task.

To understand the above differences, we can answer from the following angles

Performance: ①:GCD is closer to the bottom, while Nsoperationqueue is more advanced abstraction, so GCD is the fastest in the pursuit of performance at the bottom of the operation. This depends on using instruments for code performance analysis, if necessary

②: Transactional, sequential line, dependency between asynchronous operations. GCD needs to write more code to implement it, and Nsoperationqueue has built in these support

③: Nsoperationqueue is a better choice if the process of an asynchronous operation requires more interaction and UI rendering. In the underlying code, the tasks are less dependent on each other and require higher concurrency, and the GCD is more advantageous

The last word: Don't forget Gartner's teachings: "In about 97% of the time, we should forget the tiny performance gains." Premature optimization is the source of all evil. "Only instruments shows a real performance boost when it's necessary to use low-level gcd.

Detailed GCD How does the process of deadlock on Unix communicate?
    • UNIX mainly supports three kinds of communication methods:
    • Basic communication: Primarily used to reconcile inter-process synchronization and mutual exclusion
      • Lock file communication: Both sides of the communication can complete the mutual exclusion of the critical resource access between processes by locating certain types of files (called lock files) in a particular directory; For example, a process P1 accesses a critical resource, first to see if there is a specific type of file, and, if so, to wait for a period of time to find the lock file.
        • Record lock file
    • Pipeline communication: Adapting to large volumes of data transfer
    • IPC: Adaptable to large volumes of data transfer
The synchronization mechanism of several processes, the communication path of the process, the deadlock and the deadlock processing methods are enumerated.
    • Process synchronization mechanism atomic operation Semaphore mechanism spin-lock tube, rendezvous, distributed system

      • Ways to communicate between processes: Shared storage System Message delivery system pipeline: File System-based

      • Cause of Process deadlock: resource competition and process promotion sequence illegal

      • 4 Necessary conditions for deadlocks: mutual exclusion, request-hold, non-deprivation, loop

      • Deadlock handling: Ostrich strategies, prevention strategies, avoidance strategies, detection and unlocking deadlocks

What are the differences and connections between threads and processes?
    • A thread is the basic unit of a process.

    • Processes and threads are the basic units that are run by the programs produced by the operating system, and the system uses this basic unit to implement the concurrency of the system to the application.

    • The main difference between processes and threads is that they are different ways to manage operating system resources.

    • The process has a separate address space, and after a process crashes, it does not affect other processes in protected mode.

    • A thread is just a different execution path in a process.

    • Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, efficiency is worse.

    • But for some concurrent operations that require simultaneous and shared variables, only threads can be used, and processes cannot be used.

How do I communicate between iOS threads?
    • PerformSelector:onThread:withObject:waitUntilDone:
    • Nsmachport
      (Basic mechanism: a thread (parent thread) creates a Nsmachport object and joins the Runloop of a thread.) When a B thread (worker thread) is created, the created Nsmachport object is passed to the principal entry point, and the B thread (worker thread) can use the same port object to pass the message back to the A thread (the parent thread). )
iOS multi-threaded bottom-up implementation?
    • First figure out what a thread is, what a multithreaded
      • Mach is the first system to handle tasks in a multi-threaded manner, so the underlying implementation mechanism for multithreading is Mach-based threading
      • Mach-level threads are seldom used in development because the Mach-level threads do not provide the basic features of multithreading, and the threads are independent
    • Implementing multi-threaded scenarios in development
      • POSIX interface for C language: #include <pthread.h>
      • OC's Nsthread
      • C-GCD interface (best performance, more streamlined code)
      • OC Nsoperation and Nsoperationqueue (based on GCD)
How to solve the multi-threaded security problem? What is thread synchronization and how does it work? What is the function of a thread callback main thread method?
    • Solution: Use Locks: locks are the basis of the thread-programmed synchronization tool. Locks make it easy to protect a large area of your code so that you can ensure that your code is correct.
      1. Using POSIX mutexes;
      2. Use of the Nslock class;
      3. Use @synchronized directives and so on.
    • Methods to return to the main thread: Dispatch_async (Dispatch_get_main_queue (), ^{});
    • Role: The main thread is to display the UI interface, and the child threads are mostly data processing
Is it necessarily thread-safe to use atomic?
不是的。 atomic原子操作,系统会为setter方法加锁。 具体使用 @synchronized(self){//code } nonatomic不会为setter方法加锁。 atomic:线程安全,需要消耗大量系统资源来为属性加锁 nonatomic:非线程安全,适合内存较小的移动设备使用atomic并不能保证绝对的线程安全,对于要绝对保证线程安全的操作,还需要使用更高级的方式来处理,比如NSSpinLock、@syncronized等
Talk about your understanding of multithreaded development (the benefits of multithreading, the role of multithreading)? Are there several ways to implement multithreading in iOS?
    • Benefits:
      • Using threads can put tasks in a program that takes up a long time to work in the background
      • User interface can be more attractive, such as the user clicked a button to trigger the processing of certain events, you can pop up a progress bar to show the progress of processing
      • The operating efficiency of the program may increase
      • Threads are useful for tasks such as user input, file read and write, and network send and receive data.
    • Disadvantages:
      • If you have a large number of threads, it can affect performance because the operating system needs to switch between them.
      • More threads require more memory space.
      • The termination of a thread requires consideration of its impact on the program's operation.
    • Typically, block model data is shared across multiple threads, and it is necessary to prevent thread deadlock situations from occurring.
    • Ways to implement Multithreading:
      1. NSObject class Method//-(void) Performselectornbackground/onmainthread: (SEL) Aselector withobject: (ID) arg
      2. Nsthread
      3. Nsoperation
      4. GCD
What kind of event model is used asynchronously in OC, asynchronous implementation mechanism in iOS
    • Asynchronous non-blocking I/O (AIO)
Talk more about GCD
    1. The launch of the time IOS4 is intended to replace Nsthread (ios2.0), which is the C language framework, which automatically leverages more CPU cores and automatically manages the life cycle of the threads.

      • Two core concepts of CGD: Tasks, queues
      • Task: Write the code that executes in the block.
      • Queue: Used to hold a task.
      • Caveats: Queue! = Thread. The tasks that are stored in the queue are finally executed by the thread!. Queue principle: FIFO, LIFO (Fifo/first in First out)
    2. The queue is divided into four things: 1 serial queue 2 concurrent queue 3 Home column 4 Global queue

      • Serial queue: The task executes one after another.
      • Concurrent queues: Tasks in the queue are executed concurrently.
      • Main queue: The queue associated with the main thread, the contents of the home column will be executed in the main thread (we typically refresh the UI in the main thread).
      • Global queue: A special concurrent queue.
    3. The difference between a concurrent queue and a global queue:
      • The concurrent queue has a name that can track errors. The global queue does not have
      • In Arc, two queues do not need to consider freeing up memory, but in MRC the concurrent queue is created to require the release operation, and the global queue is only one that is not required.
      • Generally we use global queues during the development process.
    1. Two functions to perform a task

      • ' Synchronous ' execution tasks: Dispatch_sync (< #dispatch_queue_t queue#>, <#^ (void) block#>)
      • ' Async ' Execution task: Dispatch_async (dispatch_queue_t queue, <#^ (void) block#>)
    2. The difference between "synchronous" and "asynchronous":

      • "Synchronization": The task can only be performed in the ' current ' thread and does not have the ability to open a new thread.
      • "Async": You can perform tasks in a ' new ' thread, with the ability to open new threads.
    3. The execution effect of each queue:

      • Serial queues are executed synchronously, both sequentially in the current thread
      • The serial queue executes asynchronously, opening a new thread that executes sequentially in that thread
      • Parallel queues are executed synchronously, without threading, sequentially in the current thread
      • Parallel queues execute asynchronously, opening up multiple new threads, and threads are reused, unordered execution
      • The primary queue executes asynchronously, does not open new threads, and executes sequentially
      • The primary queue is executed synchronously, causing a deadlock (' main thread ' and ' home row ' waiting for each other, stuck in the main thread)
    4. Inter-thread communication: Classic case: A child thread takes a time-consuming action (such as downloading updates, etc.) on the main thread for UI refresh.

      • Classic Usage (sub-thread download (time consuming operation), main thread refresh UI):
dispatch_async(dispatch_get_global_queue(0, 0), ^{  // 执行耗时的异步操作...dispatch_async(dispatch_get_main_queue(), ^{// 回到主线程,执行UI刷新操作
    1. Deferred operation

      Call the NSObject method: [Self performselector: @selector (Run) Withobject:nil afterdelay:2.0];

      Call the self's Run method after 2 seconds

      GCD function Implementation Delay execution: Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec)), Dispatch_get_main_ Queue (), ^{

      After 2 seconds, execute the code here ... On which thread to execute, with respect to the queue type

    1. Use of queue groups:

      • Project requirements: First, two time-consuming operations are performed asynchronously, followed by the execution of two time-consuming operations, and then back to the main thread. Use queue groups (dispatch_group_t) to quickly and efficiently implement these requirements.

        dispatch_group_t group = Dispatch_group_create (); Queue Group

        dispatch_queue_t queue = dispatch_get_global_queue (0, 0); Global concurrent queues

        Dispatch_group_async (group, queue, ^{//execute operations asynchronously 1

        LongTime1

        });

        Dispatch_group_async (group, queue, ^{//asynchronous perform operation 2

        LongTime2

        });

        Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{

        Refresh data on the main thread
        Reload Data
        });

How does the GCD interior come true?
    • The core of iOS and OS X is the XNU kernel, GCD is implemented based on the XNU kernel
    • GCD APIs are all in the Libdispatch library
    • The underlying implementations of GCD are mainly dispatch queue and dispatch Source
      • Dispatch Queue: Managing block (Operations)
      • Dispatch Source: Handling events (Mach port send, Mach port receive, detection of 10 events such as process-related events)
The code executed in the GCD queue, main queue must be in main thread?
?    对于queue中所执行的代码不一定在main thread中。如果queue是在主线程中创建的,那么所执行的代码就是在主线程中执行。如果是在子线程中创建的,那么就不会在main thread中执行。?    对于main queue就是在主线程中的,因此一定会在主线程中执行。获取main queue就可以了,不需要我们创建,获取方式通过调用方法dispatchgetmain_queue来获取。
How can I synchronize several asynchronous calls with GCD? (such as loading multiple pictures asynchronously based on several URLs, and then compositing an entire image after the download is complete)
使用Dispatch Group追加block到Global Group Queue,这些block如果全部执行完毕,就会执行Main Dispatch Queue中的结束处理的block。dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, );dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, queue, ^{ /*加载图片1 */ });dispatch_group_async(group, queue, ^{ /*加载图片2 */ });dispatch_group_async(group, queue, ^{ /*加载图片3 */ });dispatch_group_notify(group, dispatch_get_main_queue(), ^{        // 合并图片});
Have a, B, C, D 4 asynchronous requests, how to judge A, B, C, D are complete execution? If you need A, B, C, D sequential execution, how to implement?
1.    对于这四个异步请求,要判断都执行完成最简单的方式就是通过GCD的group来实现:2.    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);3.    dispatch_group_t group = dispatch_group_create();4.    dispatch_group_async(group, queue, ^{ /*任务a */ });5.    dispatch_group_async(group, queue, ^{ /*任务b */ });6.    dispatch_group_async(group, queue, ^{ /*任务c */ }); 7.    dispatch_group_async(group, queue, ^{ /*任务d */ }); 8.     9.    dispatch_group_notify(group, dispatch_get_main_queue(), ^{10.        // 在a、b、c、d异步执行完成后,会回调这里11.    });当然,我们还可以使用非常老套的方法来处理,通过四个变量来标识a、b、c、d四个任务是否完成,然后在runloop中让其等待,当完成时才退出run loop。但是这样做会让后面的代码得不到执行,直到Run loop执行完毕。要求顺序执行,那么可以将任务放到串行队列中,自然就是按顺序来异步执行了
After sending 10 network requests and then receiving all the responses, how do I do the following?
从题目分析可知,10个请求要全部完成后,才执行某一功能。比如,下载10图片后合成一张大图,就需要异步全部下载完成后,才能合并成大图。做法:通过dispatch_group_t来实现,将每个请求放入到Group中,将合并成大图的操作放在dispatch_group_notify中实现。dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, queue, ^{ /*加载图片1 */ });dispatch_group_async(group, queue, ^{ /*加载图片2 */ });dispatch_group_async(group, queue, ^{ /*加载图片3 */ }); dispatch_group_notify(group, dispatch_get_main_queue(), ^{    // 合并图片});
Why did Apple abandon dispatch_get_current_queue?
    • Dispatch_get_current_queue easily cause deadlocks. Click the API to view the official notes.
What would you do if you were to implement dispatch_once?
    • Http://www.dreamingwish.com/article/gcd-guide-dispatch-once-2.html (Super detailed analysis)

    • Personally feel that the realization of the idea can be, unlocked thread synchronization programming, every thread competition is taken into account and properly handled

    • When thread a executes the block, any other threads need to wait.

    • When thread a executes the block, it should immediately mark the completion status of the task and then traverse the semaphore chain to wake up all waiting threads.
    • When thread a traverses the semaphore chain to signal, any other new incoming function threads should return directly without waiting.
    • When thread a traverses the semaphore chain to signal, if other waiting thread B is still updating or attempting to update the semaphore chain, this thread B should be guaranteed to do its job correctly: A. Return directly B. Wait on the semaphore and soon wake up again.
    • When thread B constructs semaphores, it should consider that thread a may change state at any time ("Wait", "Finish", "Traverse semaphore Chain").
    • When thread B constructs semaphores, it should be taken into account that another thread C may be updating or attempting to update the semaphore chain, and that B and C should be guaranteed to perform their tasks normally: a. Increase the link and wait on the Semaphore B. Discover that thread A has marked "done" and then directly destroys the semaphore and exits the function.
About Nsoperation:
    • Nsoperation: Abstract class, cannot be used directly, need to use its subclasses. (Similar classes also have core animations)
    • Two commonly used subclasses: Nsinvocationoperation (call) and nsblockoperation (block);
    • There is no essential difference between the two, which uses Block form to organize the code, which is relatively convenient to use.
    • Nsinvocationoperation after the Start method is called, the new thread is not opened but only executed in the current thread.
    • Nsblockoperation after calling the Start method, if the encapsulated operand >1 will open up multiple threads of execution = 1 will only be executed on the current thread.
    • The action queue created by Nsoperationqueue defaults to a global queue, and the order in which operations are executed in the queue is unordered, and dependencies need to be added if it needs to be ordered to execute in an orderly manner.
    • Operation OP3 Dependent on Operation OP2 [OP3 ADDDEPENDENCY:OP2];
    • Operation OP2 Dependent on Operation OP1 [OP2 ADDDEPENDENCY:OP1];
    • You can also set the maximum number of concurrent
    • Nsoperationqueue Nsoperation supports canceling a paused operation but an operation that is in progress cannot be canceled, which is not recoverable once it is canceled.
      • Nsoperationqueue supports KVO, can monitor whether operation is executing (isexecuted), whether it ends (isfinished), whether it is canceled (Iscanceld)
Nsoperation queue?
    • The collection class that holds the nsoperation. Can't say queue, not strictly FIFO
The difference between nsoperation and GCD
    • GCD

      1. GCD is iOS4.0 launched, mainly for the multi-core CPU is optimized, is a pure C language technology.
      2. GCD is a function that adds a task (block) to the queue (serial, parallel, Global, home column) and performs the task synchronously/asynchronously.
      3. GCD provides some functionality that Nsoperation does not have
        • Disposable execution
        • Deferred execution
        • Dispatch Group
        • GCD is a strict queue, FIFO first-out;
    • Nsoperation

      1. Nsoperation is iOS2.0 launched, iOS4.0 later rewritten the nsoperation
      2. Nsoperation is to add an operation (an asynchronous task) to a queue (a concurrent queue) and execute the specified function
      3. Convenient operation provided by Nsoperation
        • Maximum number of concurrent
        • Pausing and continuing the queue
        • Cancel all operations
        • Specifies the dependency dependency between operations, which allows asynchronous tasks to be executed synchronously.
        • Use KVO in nsoperation to listen for a operation is complete.
        • Ability to prioritize nsoperation to enable tasks in the same parallel queue to be executed sequentially
        • Inherit from the Nsoperation, add member variables and member methods on top of it, and increase the reuse of the entire code
The difference between GCD and Nsthread
    • Nsthread Specifies the method to execute by @selector, the code is scattered
    • GCD Specify the code to execute by block, the code set, all the code is written together, making the code simpler, easier to read and maintain
    • Using GCD does not require the process of managing the creation/destruction/reuse of threads! Programmers don't care about the thread's life cycle
    • If you want to open multiple threads nsthread must instantiate multiple thread objects
    • Nsthread by the NSObject classification method to achieve the inter-thread communication,
Why do I have to cancel/resume the queue?
    • Operations in the queue are generally canceled after a memory warning.
    • To ensure that the scorllview is smooth when scrolling, it usually pauses all operations in the queue at the beginning of scrolling, and resumes operations after scrolling is complete.
What is the method for creating a thread in Object C? What is the method if you execute code in the main thread? What is the method if you want to delay execution of code?
线程创建有三种方法:使用NSThread创建、使用GCD的dispatch、使用子类化的NSOperation,然后将其加入NSOperationQueue;NSThread创建线程的三种方法: NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"nil"]; [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"我是分离出来的子线程"];[self performSelectorInBackground:@selector(run:) withObject:@"我是后台线程"];在主线程执行代码,就调用performSelectorOnMainThread方法。如果想延时执行代码可以调用performSelector:onThread:withObject:waitUntilDone:方法;GCD:利用异步函数dispatch_async()创建子线程。在主线程执行代码,dispatch_async(dispatch_get_main_queue(), ^{});延迟执行代码(延迟·可以控制代码在哪个线程执行):dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{});NSOperationQueue:使用NSOperation的子类封装操作,再将操作添加到NSOperationQueue创建的队列中,实现多线程。在主线程执行代码,只要将封装代码的NSOperation对象添加到主队列就可以了。
The following about thread management errors are
A. GCD所用的开销要比NSThread大B. 可以在子线程中修改UI元素C. NSOperationQueue是比NSthread更高层的封装D. GCD可以根据不同优先级分配线程
    • Reference Answer: B
    • Reason: First, the UI element's update must be in the main thread. GCD is used in conjunction with block, the block needs to automatically capture the context variable information and so on, so it needs more resources, so it is more expensive than nsthread. Nsoperationqueue with Nsoperation, it is easier to manipulate threads than Nsthread. GCD provides multiple priorities, and we can assign threads to us automatically based on the priority we set.

iOS multi-Threading--deep parsing

Related Article

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.