The difference between ios multithreading and process is reprinted by ios multithreading process.

Source: Internet
Author: User
Tags strtok

Differences between ios multithreading and process (reprinted) and ios multithreading process reprinted

I really want to write something about multi-process and multi-thread. But every time I want to write something about them, I always want to work hard and never get started.

Today, I finally made up my mind to write something. I can fix it later.

 

I. Why do I need multi-process (or multi-thread) and concurrency?

This issue may not be a problem. But for those who do not have access to too many process programming, they do not feel the charm and necessity of concurrency.

I think, as long as you are not the person who writes the int main () code all day, you may experience insufficient code response or the sweetness of concurrent programming. It's like a fast-food waiter who needs to receive a meal from a customer at the front-end and receive a takeout by phone. Without separation, you will surely be overwhelmed. Fortunately, there is indeed such a technology that allows you to stand apart like Sun Wukong and be able to handle all situations with ease. This is multi-process/thread technology.

Concurrency Technology is a technology that allows you to execute multiple tasks at the same time. Your code will not only be executed in a regular line from top to bottom, from left to right. You can communicate with your customers by line in the main function, and by line, you have already delivered your takeout to other customers.

 

So why concurrency? Because we need more powerful functions and provide more services, concurrency is essential.

 

Ii. Multi-Process

What is a process. The most intuitive one is pid. The official saying is: a process is an execution activity of a program on a computer.

To put it simply, when the following code is executed:

View plainview plain

 

Enter the main function. This is a process. The process pid will be printed and then run to return. The function will exit. Then, because the function is the only execution of the process, therefore, the process also exits after return.

 

Look at the multi-process. In linux, the call to create a sub-process is fork ();

 

View plainview plain

 

I am the child process, my process id is 15806 the exit pid: 15806 I am the parent process, my process id is 15805 the exit pid: 15805

This is the running result of the gcc test.

 

With regard to the fork function, the function is to generate sub-processes. As mentioned above, processes are executed process activities.

In this case, fork generates a sub-process, which returns two times, returns 0 at a time, and executes the following code in sequence. This is a sub-process.

The pid of the child process is returned at one time, and the following code is also executed in sequence. This is the parent process.

(Why does the parent process need to obtain the child process pid? There are many reasons for this. One of the reasons is: Look at the final wait and you will know that the parent process will wait for the end of the Child process to process its task_struct structure. Otherwise, a zombie process will be generated, which is far away, google if you are interested ).

If fork fails,-1 is returned.

Additionally, atexit (print_exit); the required parameter must be the function call address.

Is print_exit a function name or a function pointer? The answer is the function pointer. function names are always useless strings.

Rules in a book: function names are equivalent to function pointers when used for non-function calls.

 

Speaking of sub-process as an additional process, what is the connection and difference between the sub-process and the parent process?

I would like to suggest you look at the Linux kernel annotations (if you are interested, you can check them to understand them in essence). In short, after fork, the child process will copy the task_struct structure of the parent process, and allocate a physical page for the stack of the sub-process. Theoretically, the child process should completely copy the heap, stack, and data space of the parent process, but the two share the body segment.

About write-time replication: Since generally fork is followed by exec, the current fork uses the write-time replication technology, which means data segment, heap, stack, it is not copied at the beginning, shared by the parent and child processes, and the memory is set to read-only. The kernel copies the copy of the memory to be modified until the child process tries to write these areas. This improves the efficiency of fork.

 

Iii. Multithreading

A thread is a allocable unit of executable code. This name comes from the concept of "execution clue. In a thread-based multi-task environment, all processes have at least one thread, but they can have multiple tasks. This means that a single program can execute two or more tasks concurrently.

 

In short, a thread divides a process into multiple parts, each of which can be an independent process. This is obviously different from multi-process. The process is a copy process, and the thread just cut a river into many streams. It does not copy these additional overhead, but it is only an existing river, and it is converted into many small processes by multithreading technology with almost no overhead, its greatness lies in its small amount of system overhead. (Of course, the great things are followed by various re-entry problems, which will be compared later ).

Let's take a look at the multi-threaded system calls provided by linux:

 

Int pthread_create (pthread_t * restrict tidp, const pthread_attr_t * restrict attr, void * (* start_rtn) (void), void * restrict arg );

Returns: 0 if OK, error number on failure

The first parameter is the pointer to the thread identifier. The second parameter is used to set the thread attributes. The third parameter is the starting address of the thread-running function. The last parameter is the parameter used to run the function.

 

View plainview plain

 

This multi-threaded example should be very clear. The main thread does its own thing and generates two sub-threads. Task 1 is separated and left self-defeating. Task 2 continues to deliver food and needs to wait for the return. (For this reason, remember to say that the zombie process is mentioned before, and the thread also needs to wait. If you don't want to wait, set the thread to a separate thread)

Additionally, to compile and use the thread code in linux, you must call the pthread library. Compile as follows:

Gcc-o pthrea-pthread pthrea. c

 

Iv. Comparison and precautions

 

1. You should have an intuitive understanding of multi-process and multi-thread. To sum up the differences between multi-process and multi-thread, you can say that the former has a high overhead while the latter has a low overhead. Indeed, this is the most basic difference.

2. reusability of thread functions:

When it comes to function re-entry and thread security, I am lazy and reference some summary on the Internet.

 

Thread security: intuitive concept. Generally, a function is called thread-safe. It always produces correct results when it is repeatedly called by multiple concurrent threads.

 

 

 

 

 

Reentrant: The concept is basically not a formal and complete explanation, but it is more strict than the thread security requirements. Based on experience, the so-called "re-import", the common situation is that when the program runs to a function foo (), it receives a signal, so it suspends the function currently being executed, to the signal processing function, and the execution process of the signal processing function also enters the just-executed function foo (), so the so-called re-import occurs. In this case, if foo () can run correctly and the previously paused foo () can run correctly after processing is completed, it indicates that it can be reentrant.

Conditions for thread security:

To ensure function thread security, the main consideration is the shared variables between threads. Different threads belonging to the same process will share the global zone and heap in the process memory space, while the private thread space mainly includes stacks and registers. Therefore, for different threads of the same process, the local variables of each thread are private, while global variables, local static variables, and variables allocated to the heap are shared. When accessing these shared variables, If You Want To ensure thread security, you must lock them.

Reentrant judgment conditions:

To ensure that the function can be reentrant, the following conditions must be met:

1. Do not use static or global data within the function. 2. Do not return static or global data. All data is provided by the function caller. 3. Use local data or make local copies of global data to protect global data. 4. Do not call the reentrant function.

 

The reentrant function is not equivalent to thread security. Generally, the reentrant function is thread-safe, but in turn it is not necessarily true. Their relationships can be expressed as follows:

 

 

For example, the strtok function is neither reentrant nor thread-safe. The strtok with a lock is not reentrant, but thread-safe. The strtok_r function is reentrant, it is also thread-safe.

 

If our thread functions are not thread-safe, the possible consequence of multi-threaded calls is obvious-shared variable values are accessed by different threads, unexpected changes may occur, leading to program errors or even crashes.

 

3. About IPC (inter-process communication)

Communication between processes is inevitable due to the concurrent coordination of multiple processes.

List the common linux IPC.

Introduction to several main methods for inter-process communication in linux:

Maybe you have doubts. What should I do if multiple threads need to communicate? As mentioned above, most multithreading is in the same process. They share the global variables of the process. We can use global variables to implement inter-thread communication. For communication between two threads in different processes, refer to inter-process communication directly.

 

4. Thread Stack

Let's talk about the thread's own stack.

Yes. After a subthread is generated, it obtains the stack space of a part of the process as its nominal independent private space. (Why is it nominal ?) Because these threads belong to the same process, as long as other threads obtain some data pointers on your private stack, other threads can freely access the data variables in your nominal private space. (Note: multiple processes are not allowed. Because different processes have the same virtual address, it is basically impossible to map to the same physical address)

 

 

5. fork in the Child thread

 

I have read it several times and asked why an error occurred when calling system or fork in the subthread function, or is the child process generated by fork completely copying the parent process?

As long as your thread function meets the preceding requirements, it is normal.

 

View plainview plain

 

 

The above code can call the ls command normally.

 

However, when multiple processes (sub-processes also call thread functions) and multithreading are called at the same time, deadlocks may occur in the function body.

For specific examples, refer to this article.

 

Http://www.cppblog.com/lymons/archive/2008/06/01/51836.aspx

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.