Context switch (context switch), also known as environment switch, computer terminology, is a state (context) that stores and reconstructs the CPU, so it allows multiple Processes can share the computing process of a single CPU resource. When you want to swap processes on the CPU, you must first store the status of the current process, and then read the status of the process to be executed back to the CPU.
When to exchange?
There are three possible situations where context exchange will occur, namely:
Multi-tasking
The most common one is that in some scheduling algorithms, a trip sometimes needs to temporarily leave the CPU to allow another trip to come in and run on the CPU. In a preemptive multiplexing system, each trip will be executed in turn for a variable length of time. These time periods are called time slices. If the process does not voluntarily give up the CPU (for example, when performing I/O operations, the process needs to give up the right to use the CPU), when the time limit expires, the system will generate a timed interrupt, and the operating system will schedule other processes to be executed. This mechanism is used to ensure that the CPU is not monopolized by processes that rely more on processor operations. If there is no scheduled interrupt, the process will continue to execute unless it voluntarily gives up the CPU. For trips with a lot of I/O instructions, they often cannot be executed for long before they need to give up the CPU; while trips that rely more on the processor have relatively fewer I/O operations, but can continue to use the CPU, forming a monopoly. Phenomenon. This is the Convoy effect.
Interrupt processing
When receiving an interrupt (Interrupt), the CPU must perform context switching.
Exchange of user mode or kernel mode
When the exchange of user mode and kernel mode occurs, there is no need for context exchange; and the difference between user mode and kernel mode The exchange itself is not a context exchange. However, depending on the operating system, sometimes a context exchange step is performed at this time.
Context exchange:Specific steps
In an exchange, the status of the first trip should be recorded somewhere, so that when When the scheduler returns to this schedule, it can rebuild the schedule and continue the operation.
The so-called "trip status" here includes all registers used by this trip, especially the program counter; plus all specific data that the operating system may require. These data are generally stored in a data structure called a process control block (PCB).
Context exchange: implemented by software or hardware
Context exchange can be divided into mainly implemented by software or implemented by hardware. Some CPUs, such as Intel 80386 or higher-end processors of the same series, have hardware designs that support context switching.