IOS multithreading principle and ios multithreading Principle

Source: Internet
Author: User

IOS multithreading principle and ios multithreading Principle

The thread application in the iPhone is not uncontrolled. Official documents show that the stack size of the main thread in the iPhone OS is 1 MB, and that of the second thread is kb at the beginning. The value cannot be changed through the compiler switch or the thread API function. Only the main thread can directly modify the UI.

1. Thread Overview

Some programs are a straight line, starting from the beginning to the end; some programs are a circle that repeats until it is cut off. A straight line is like a simple Hello World. After printing is completed, its life cycle ends, just like a flash in the pan. The circle is like an operating system and runs until you shut down.
A running program is a process or a task. A process contains at least one thread, and a thread is the execution flow of the program. When a program in Mac and iOS is started and a process is created, a thread starts to run. This thread is called the main thread. The status of the main thread in the program is different from that of other threads. It is the final parent thread of other threads, and all interface display operations, that is, AppKit or UIKit operations, must be performed in the main thread.
Each process in the system has its own virtual memory space, while multiple threads in the same process share the memory space of the process. Each time a new thread is created, some memory is required (for example, each thread has its own Stack space) and a certain amount of CPU time is consumed. In addition, when multiple threads compete for the same resource, pay attention to thread security issues.

 

Ii. Create a thread

Creating a New thread is to add an execution stream to the process. The execution stream must have the code to be executed. Therefore, to create a new thread, you must provide a function or method as the thread entry.

1. Use NSThread

NSThread provides a way to create a thread and a method to check whether the current thread is the main thread. There are two ways to create a new thread using NSThread:

  • 1. Create an NSThread object and call its start method. For the creation of NSThread objects in this way, you can use the method of a target object to initialize an NSThread object, or create a subclass that inherits the NSThread class to implement its main method, then, directly create the object of this subclass.
  • 2. Use detachNewThreadSelector: toTarget: withObject: This class method to create a thread. This method directly uses the method of the target object as the thread startup entry.
2. Use NSObject

In fact, NSObject directly adds multi-thread support, allowing a method of the object to run in the background. For example:

 
 
  1. [myObj performSelectorInBackground:@selector(doSomething) withObject:nil]; 
3. POSIX Thread

Because Mac and iOS are both based on the Darwin system, The XUN kernel of the Darwin system is based on Mach and BSD and inherits the POSIX interface of BSD, therefore, you can directly use POSIX thread-related interfaces to use threads.

The interface for creating a thread is pthread_create. Of course, you can set the thread attributes through relevant functions before creating the thread. The following is a simple example of POSIX thread usage.

 
 
  1. // //  main.c //  pthread // //  Created by Lu Kejin on 1/27/12. //  Copyright (c) 2012 Taobao.com. Al 
  Iii. multithreading advancedNSOperation & NSOperationQueue

Many times we use multithreading and need to control the number of concurrent threads. After all, threads consume system resources. when too many threads run simultaneously in the program, the system will inevitably slow down. Therefore, we usually control the number of concurrent running threads.

NSOperation can encapsulate our operations, and then put the created NSOperation object into NSOperationQueue. OperationQueue starts a new thread to execute operations in the queue, the concurrency of OperationQueue can be set as follows:

 
 
  1. - (void)setMaxConcurrentOperationCount:(NSInteger)count 
GCD

GCD, short for Grand Central Dispatch, is a series of BSD-level interfaces that were introduced after Mac 10.6 and iOS4.0. Now NSOperation and NSOperationQueue are implemented based on GCD. Currently, this feature has been ported to FreeBSD. You can view the libdispatch open-source project.

For example, a large image is displayed in UIImageView.

 
 
  1. dispatch_queue_t imageDownloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(imageDownloa 

Of course, GCD has many excellent functions in addition to multi-thread processing. It is built on a powerful kqueue and ensures the efficiency.

 

4. Inter-thread Communication

In essence, inter-thread communication and inter-process communication are similar. Inter-thread communication refers to data transmission between two execution streams in a process, just as a one-way flow long gap is dug between two parallel rivers, so that the water in a river can flow into another river, and the material is transferred.

1. datagmselect On The Thread

The Framework provides us with a way to forcibly execute methods in a thread. If two non-main threads need to communicate with each other, you can first register your current thread object to a global object, so that you can obtain the thread object of the other party, then we can use the following method for inter-thread communication. Because the main thread is special, the framework directly provides the method for executing in the output thread.

 
 
  1. @interface NSObject (NSThreadPerformAdditions) - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUnti 

2. Mach Port
In the running ing a Port-Based Input Source section of the Run Pool section of Apple's Thread Programming Guide, there is an example of using the Mach Port for inter-Thread communication. The essence is that the parent thread creates an NSMachPort object and transmits it to the subthread as a parameter when creating the subthread, in this way, the thread can send messages to the passed NSMachPort object. If you want the parent thread to send messages to the subthread, then, the sub-thread can send a special message to the parent thread, passing in another NSMachPort object created by itself, so that the parent thread holds the port object created by the sub-thread, you can send a message to the port object of this subthread.

Of course, you need to set delegate and schdule for each port object to the RunLoop of the thread where you are located. In this way, the delegate method for processing the port message will be called after the message is sent, you can process the message by yourself.

 

5. RunLoop

RunLoop is literally a running loop, which is also good. It is indeed a loop concept or, accurately, a loop in a thread. At the beginning of this article, we mentioned that some programs are a circle. This circle is essentially the so-called RunLoop here, which is a loop, but many features are added to this loop.
First, you need to check whether there are any events to be processed at the beginning of the loop body. If yes, you need to process them. If not, you need to sleep to save CPU time. Therefore, the focus is on the event to be processed. In RunLoop, there are two types of events to be processed: one is the input source and the other is the timer, A timer is an operation that requires scheduled execution. The input source can be classified into three types: mongomselector source, Mach port-based source, and custom source. You can add your own source when programming. RunLoop also has the concept of Observer. You can add your own Observer to RunLoop to monitor the running process of RunLoop. CFRunLoop. h defines the types of all observers:

 
 
  1. enum CFRunLoopActivity { kCFRunLoopEntry = (1 << 0), kCFRunLoopBeforeTimers = (1 << 1), kCFRunLoopBeforeSources = ( 

If you have used a select System Call and written a program, you can quickly understand the concept of the runloop event source. Essentially, the event source mechanism is similar to select, which is a multiplexing IO implementation, in a thread, what we need to do is not a single task. If we need to process clock events, we need to process user touch events, and we need to accept data sent from the remote network, add all the things that need to be done to the event source, and check whether the event source has the data to be processed at the beginning of each loop. If so, process the data. Take a specific application for example. NSURLConnection network data requests are asynchronous by default. The implementation principle is to add them as event sources to the current RunLoop after creation, the process of waiting for network response and network data acceptance is completed in a newly created independent thread, when this thread processes a certain stage, such as receiving the response from the other party or receiving network data, it notifies the previous thread to execute its related delegate method. Therefore, in Cocoa, we often see scheduleInRunLoop: forMode: This method is used to add it to the event source. When an event is detected, the related delegate method is called. For the CoreFoundation layer, the common mode is to create an input source, and then add the input source to the RunLoop through the CFRunLoopAddSource function. After a related event occurs, related callback functions will be called. For example, CFSocket usage. In addition, RunLoop also has a concept of running mode. Every running cycle must run in a certain mode, and the existence of the mode is to filter the event source and observer, only the event sources and observers that are consistent with the current RunLoop running mode will be activated.

Each thread has its own RunLoop, but by default, the RunLoop of a non-main thread does not run. You need to add at least one event source for the RunLoop and then run it. Generally, we do not need to enable the RunLoop of a thread unless you need to detect an event for a long time in a separate thread.


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.