What is a process?
an application running in the operating system
For example, open QQ and WeChat at the same time; the operating system will start two processes respectively
Each process is independent, and each process runs in its dedicated and protected memory space
In Windows, you can view running processes through the Task Manager
What is a thread?
For a process to perform tasks, it must have threads (at least one thread per process)
All tasks of a process are executed in threads
For example, using Kugou to play music and using Thunderbolt to download files all need to be executed in a thread
serialization of threads
Execution of tasks in 1 thread is serial
If you want to execute multiple tasks in 1 thread, then only execute the tasks sequentially one by one
At the same time, 1 thread can only execute 1 task
For example, download 3 files in 1 thread (file A, file B, file C)
Multithreading
Multiple threads can be opened in one process, and all threads can execute different tasks in parallel (simultaneously)
Multithreading technology can improve the execution efficiency of the program
For example, open 3 threads at the same time to download 3 files respectively
The principle of multithreading
At the same time, 1 core of the CPU can only process 1 thread
Multi-threaded concurrent (simultaneous) execution, in fact, the CPU quickly schedules (switches) between multiple threads
If the CPU schedules threads fast enough, it creates the illusion of multi-threaded concurrent execution
If it is a multi-core CPU, it is truly realized that multiple threads execute simultaneously
If there are too many threads:
The CPU will be scheduled among N threads, consuming a lot of CPU resources, and the CPU will be exhausted
As a result, the frequency that each thread is scheduled to be executed will be reduced (the execution efficiency of the thread will be reduced)
Advantages and disadvantages of multithreading
advantage:
1. Can properly improve the execution efficiency of the program
2. Can properly improve resource utilization (CPU, memory utilization)
shortcoming:
1. Opening a thread needs to take up a certain amount of memory space. If a large number of threads are opened, it will take up a lot of memory space.
2. The more threads, the greater the CPU overhead on scheduling threads
3. Programming is more complicated