A, definitions,
- Process is a running activity on a data set of a program with certain independent functions. Process is a basic unit of resource allocation and scheduling in the system.
- Thread is an entity of process and the smallest unit of system scheduling. A thread has virtually no system resources of its own, only a few resources that are essential to running (such as a program counter, a set of registers, and a stack), but it can share all the resources owned by a process with other threads that belong to the same process.
Second, the relationship between
- One thread can create and destroy another thread; Multiple threads in the same process can execute concurrently.
- Compared to a process, a thread is a concept that is closer to an execution body. It can share data with other threads in the same process, but has its own stack space, and has a separate execution sequence.
Third, the difference between
- Environment: Can run multiple processes (programs) at the same time in the operating system; Multiple threads execute simultaneously in the same process (with CPU scheduling, only one thread executes in each slice)
- Address space: Threads of the same process share the address space of the same process, while processes are independent of each other.
- Resource ownership: Threads in the same process share the resources of the same process, such as memory, I/O, and CPU, but resources between processes are independent. The crash of one process in protected mode does not affect other processes, but the crash of one thread kills the entire process. So multi-processing is more robust than multi-threading. Process switchover consumes large resources and is efficient. So when it comes to frequent switching, threads are better than processes. Also, if you require concurrent operations that share variables at the same time, use threads instead of processes.
- Execution process: Each independent process has a program run entry, sequential execution sequence, and program entry. However, threads cannot execute independently and must depend on the application, which provides multiple thread execution control.
- Fundamental difference: Process is the basic unit of operating system resource allocation, while thread is the smallest unit of operating system task scheduling and execution.
Four, advantages and disadvantages
- Thread execution costs little, but is not conducive to resource management and protection. Threads are suitable for running on SMP machines (dual CPU systems).
- Process execution is expensive, but it can manage and protect resources well. Processes can be moved forward across machines.
Five, when to use multi-process, when to use multi-thread?
- Multiple processes are used when the requirements for resource management and protection are high and the cost and efficiency are not limited.
- Requires high efficiency, frequent switching, resource protection management requirements are not very high, use multithreading.