CPU context switching

In high-performance programming, we often come into contact with multi-threading. At first, we always thought that multi-threaded parallel execution is faster than single-threaded execution. However, the actual situation is that multi-threads need to compete for IO devices or compete for lock resources, which often leads to faster execution than If it is not single-threaded, why use multi-threading? Let's talk a little here

There are several advantages to using multithreading

1. Using multi-threading on multi-core CPUs can improve resource utilization

2. The modular programming model of multi-threading. If you are stuck on a long-time task in a single thread, you will not move after that, which is very embarrassing. Multithreading can divide the program into several modules with relatively independent functions, and assign a thread to handle this time-consuming task

3. Multithreading has several advantages over multiprocessing. One is that the startup switching of threads is much smaller than that of processes. The other is that information can also be shared between threads, while inter-process communication requires a special message passing mechanism

 

Closer to home, a concept that is often mentioned in multithreading is the context switch. Its precise definition can refer to: http://www.linfo.org/context_switch.html  . Multitasking systems often need to perform multiple tasks at the same time. When the number of tasks is greater than the number of CPUs, how can users feel that these tasks are being performed at the same time? The designer of the operating system uses the time slice rotation method. The CPU gives each task a certain amount of time. When the time slice time is used up, the state of the current task is saved. After loading the state of the next task, the service continues. next task. The state of the task is saved and reloaded. This process is called context switching.

 

For the preemptive operating systems that we often use, there are probably several reasons for context switching: 1. The time slice of the current task execution runs out, and the CPU normally schedules the next task 2. The current execution task encounters IO blocking, The scheduler suspends this task and executes the next task. 3. Multiple tasks snatch lock resources. If the current task is not seized, it is suspended by the scheduler. 4. User code suspends the current task 5. Hardware terminal. In general, it is the switching of the current task caused by various reasons.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326278633&siteId=291194637