IOS multi-thread management & lt; 1 & gt; two or three things you must know about multithreading, ios multi-thread

Source: Internet
Author: User

IOS multi-thread management <1> what you must know about multithreading: ios multi-thread management

/*

Not a technical Article, but a way to record your daily learning

---------------------------- The journey of programmers is the sea of stars

*/

 

[1] what is multithreading?

Before multithreading, many people confuse processes, threads, Asynchronization, synchronization, serial, and concurrency. The concept obfuscation is very serious, and even when some third-party class libraries are used, I don't know how it uses data requests, asynchronous, synchronous, multi-thread, or single-thread. Here I have summarized the multi-threading knowledge I have been dealing with over the past few days and clarified the conceptual content.

Process: in IOS systems, a task such as an application is often used as a process.

To execute a task, one process must have at least one thread (each process must have at least one thread)

Thread: The component of a process. It is a code block that is repeatedly used by a process.

A thread is the basic execution unit of a process. All tasks of a process (Program) are executed in the thread.

For example, playing music with cool dogs and downloading movies with thunder all need to be executed in the thread.

Features: a single thread can only execute the same task at the same time. If multiple tasks are handed over to the same task for completion,

Then the thread will execute a task and then execute the next task until all the tasks are completed.

[Multi-thread explanation ]:

Based on the characteristics of processes and threads, we can open up multiple threads in a process. They can execute different tasks in parallel (that is, synchronize time), like a process as a project team, the thread is a member of the project team. Multiple Threads can execute different tasks at the same time, just as the project team members can have different division of labor at the same time, for example, the artist and the programmer have different project tasks.

Note that in the single-core era, the CPU cannot execute multiple threads at the same time! WTF!

Although it sounds unacceptable, it does. The CPU can only execute one thread at a time. It seems that multiple threads can work simultaneously, this is because the CPU switches back and forth between multiple threads. If the cpu switches back and forth fast enough, it creates the illusion of multi-thread concurrent execution.

In the multi-core era, the kernel-level structure uses a preemptible approach to arrange the next thread on the idle kernel. Here we will not go into details, whether it is a single-core or multi-core approach, multiple Threads increase the requirement for CPU work.

Due to this reason, when too many threads exist, the CPU resources will be occupied too much, and the speed of data processing and resources will also decrease, therefore, we should try to control the number of multithreading in a process. (The main thread occupies 1 MB by default, and the sub-thread occupies KB)

Advantages of multithreading: it can improve program execution efficiency and resource utilization.

Disadvantages of multithreading: both the start and exit of a thread require memory space to support, and the complexity of the program is also increased,

It is not conducive to reading and understanding. When there are more threads, the CPU overhead of the entire process will increase.

To use multithreading, you need to pay more attention to this content. You cannot start a new thread at will.

 

[2] main thread and secondary thread (worker thread)

Main thread: a main thread exists in each process. All UI control construction, gesture drag and drop, and view scrolling are implemented in the main thread.

We often need to do some time-consuming work, such as data requests, Loop Data Acquisition or processing content. In these cases, the main thread is bundled and the entire view screen cannot be clicked, in the case of false positives, this is fatal to the user experience. To avoid such cases, we often adopt the method of thread opening.

Sub-thread: it is also called a working thread. Its main function is to share the tasks of the main thread and prevent the screen from false-dead accidents.

[3] serial and parallel:

Serial: When a thread is used to process multiple tasks, it must be executed one by one in sequence.

Concurrency: multiple threads simultaneously execute different tasks.

[4] NSThread simple Multithreading

For NSThread, it is a simple method to enable the multithreading mode. By instantiating its object in the main thread and executing the start method (NSThread object initialized by class method is automatically executed), you can simply implement a thread.

<1> simple multi-thread implementation example

// Create two buttons in the view-(void) creatUIButton {NSArray * arr = @ [@ "thread 1", @ "thread 2"]; for (int I = 0; I <2; I ++) {UIButton * btn = [UIButton buttonWithType: UIButtonTypeCustom]; btn. frame = CGRectMake (110,100 + 100 * I, 100, 30); btn. tag = I + 1; btn. backgroundColor = [UIColor grayColor]; [btn setTitle: arr [I] forState: UIControlStateNormal]; [btn setTitleColor: [UIColor cyanColor] forState: UIControlStateNormal]; [btn addTarget: self action: @ Selector (pressBtn :) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: btn] ;}// click the event of the execution button-(void) pressBtn :( id) sender {// build the sub-thread UIButton * btn = (UIButton *) sender; // concurrent operations by multiple threads do not affect if (btn. tag = 1) {// thread object created by the handler class method/* parameter explanation: the first parameter is the parameter passed by the selector method, the second parameter is the method responder, and the third object is the parameter passed, is the OC object */NSNumber * num = @ 10; [NSThread detachNewThreadSelector: @ selector (threadMain1 :) toTarget: self withObject: num]; // use the class method to create a line Thread object. You do not need to manually enable the thread. As long as the thread is created, the thread method is automatically called.} Else {NSNumber * num = @ 10; // producer uses the instance method to create a thread object. However, you must manually enable the NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (threadMain2 :) object: num]; // manually enable the thread [thread start] ;}// thread 1 to execute code-(void) threadMain1 :( NSNumber *) num {NSLog (@ "start from thread 1 >>>>>>>>"); for (int I = 0; I <[num intValue]; I ++) {NSLog (@ "thread 1 >>> I = % d", I); [NSThread sleepForTimeInterval: 0.1]; // thread sleep for 0.5 seconds} NSLog (@ "thread 1 ends"); // The thread ends Exit (disappear)} // thread 2 executes code-(void) threadMain2 :( NSNumber *) num {NSLog (@ "thread 2 starts! -------------! "); For (int I = 0; I <[num intValue]; I ++) {NSLog (@" thread 2 I = % d ", I * 1000 ); [NSThread sleepForTimeInterval: 0.3]; // 0.5 seconds of thread sleep} NSLog (@ "thread 2 ends ");}

------- In this instance, click thread 1, and then click thread 2.

If two click events are executed in the main thread, how will they be executed?

Many people must be aware of this. After clicking the first button and then clicking the second button, their click events are conducted in sequence.

When the click event of Button 1 is not completed, the click event of Button 2 does not respond.

So how would the two click events executed in the second thread be executed?

Let's look at the execution results of this instance.

It can be seen that when the click event of thread 1 is not over, click thread 2 and the program immediately starts the thread 2 method. Therefore, we can know that:

Multithreading will not be affected by each other. As long as a thread is opened up from the main thread, it can independently complete the tasks you have arranged. We can also print some symbolic content in the main thread. It can be seen that the task of the main thread will not be terminated because of the second thread, it will continue to execute its own code instead of waiting for the end of the next thread.

 

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.