What are processes and threads?
First, you need to understand the concept of CPU. All operations on a computer are performed by the CPU. The operations that the CPU will perform are divided into tasks, which we can understand as processes, and these tasks are divided into smaller fine-grained sub-tasks, which are called threads
The CPU executes tasks in turn, and each task goes through the following phases:
- Load context
- perform
- Save context
In other words, every process goes through the same process from loading, executing, to switching to the next process, and our CPU does this process switching all the time
Processes can be divided into smaller threads that can switch back and forth like processes, but do not need to load and save context because they share context
The difference between processes and threads
Here is a brief summary of the differences between processes and threads.
- Different in nature: process is the basic unit of resource allocation, while thread is the basic unit of CPU operation and scheduling
- Different ownership: An operating system can have many processes, and a process can have many threads
- Overhead is different: process creation, destruction, and switching are much more expensive than threads
- Owning resources is different: Each process has its own memory and resources that are shared by threads in a process
- Different communication modes: processes can communicate through channels, message queues, shared memory, semaphores, and sockets, while threads mainly communicate through shared variables and their variants
- Different control and influence capabilities: Child processes cannot control parent processes, and exceptions in one process generally do not affect other processes. The child thread can control the parent thread, and if the main thread is abnormal, it affects its process and other threads
- Different expansion ability: multi-process can be easily extended to multi-machine distributed system, multi-thread to extend to multi-machine is very difficult
- CPU utilization is different: processes have low CPU utilization because of the additional context switch overhead; Threads have high CPU utilization because switching is easy
- Reliability difference: Processes are more reliable than threads