First of all, our problem is , What is a thread ?

A thread is an execution flow in a process , yes CPU Basic unit for scheduling , There can be multiple threads in a process . stay Linux lower , Thread execution flow is through PCB Realized , And there may be more than one in a process PCB, these PCB Share most resources in the same process , It can also be called
Lightweight process .(Linux The next process is the basic unit of resource allocation in the system )

Shared virtual address space between threads ( Code snippets and data snippets ), File descriptor table , Signal processing mode , Working path, etc , Unique wired process stack between threads , register ( Context data ), Signal shielding word ( Signal blocking set ), priority ,errno, Thread identifier, etc .
Multithreading and multiprocessing have common advantages in multitasking :

stay CPU When resources are sufficient , Parallel task processing can be realized , increase of efficiency . But the more threads and processes, the better , stay IO In intensive programs , A lot of work is done in the program IO operation , yes CPU Low resource requirements , Therefore, the greater the number of execution flows, the higher the efficiency , But in CPU In intensive programs , A large number of data operations are carried out in the program , yes CPU High resource requirements , At this time, too many execution flows will increase the scheduling cost ( More switching time ), At this time, the best number of execution streams is CPU Number of cores +1.
Multithreading also has its unique advantages :
1. Shared virtual address space , Therefore, inter thread communication is more flexible , except IPC In addition to the four communication modes , You can also use global variables , Inter thread communication through function parameter passing .
2. Lower cost of thread creation and destruction
3. The cost of thread scheduling switching in the same process is lower
Disadvantages of multithreading multitasking :
1. Low robustness ( Robustness refers to general errors in the running process of a program , The program will automatically perform error handling functions . In short, it refers to the ability to continue running even if there is an error )
2. Some system calls and exceptions are generated for the entire process ( for example exit Interface , Exit all threads directly )
in the majority of cases , It's better to use multithreading , However, it is better to use multi process in scenarios requiring high stability ( for example shell in )