Detailed Context Switching and Process Scheduling

Context switching in detail

1. The concept of context switching

上下文切换可以认为是内核(操作系统的核心)在 CPU 上对于进程(包括线程)进行以下的活动:
(1)挂起一个进程,将这个进程在 CPU 中的状态(上下文)存储于内存中的某处,
(2)在内存中检索下一个进程的上下文并将其在 CPU 的寄存器中恢复
(3)跳转到程序计数器所指向的位置(即跳转到进程被中断时的代码行),以恢复该进程。

Context switching is sometimes described as the kernel suspending the process currently executed by the CPU and then continuing to execute one of the previously suspended processes (process switching). The information to be operated for context switching is stored in the PCB for easy access. Context switching is very frequent, many times per second, so our operating system is required to be real-time. Real-time performance means that we control the time of each operation within 10ms. The average time of arm operating system is 1.5ms.

2. When does the context switch happen?

  • Interrupt: When an interrupt occurs, the CPU will context switch the program that initiated the interrupt request with the running program (a simple example, your CPU is performing a certain operation, and suddenly my mouse clicks, if the priority is too high, you Will immediately execute the mouse click event)
  • Multitasking: In the case of multitasking, each task has a corresponding time slice, so context switching occurs.

Process scheduling

After talking about context switching, let's talk about process scheduling. There are three ways of process scheduling.

  • First come, first serve : This process is very simple. Each process scheduling selects the job that enters the queue first, and gives the processor to the processor. After the process is completed, the processor is abandoned. Job scheduling is to allocate memory and create a process.
  • Short job priority : Every job scheduling finds a job with the shortest time in the ready queue, and allocates memory to it to run. Process scheduling is for the processor.
  • High priority : Whoever has the higher priority will be called first.
    • Non-preemptive priority scheduling: Wait for each job to be processed, and then find a job with the highest priority in the ready queue for execution.
    • Preemptive priority scheduling: A job with a higher priority than the running program comes, and the CPU immediately stops the current job and executes the higher priority job.
  • High response ratio priority : This method is (waiting time + service time)/service time. When this ratio is the highest, it is called first, but the corresponding ratio must be calculated first.

There are several situations in process scheduling:

  • Priority inversion: Low priority has resources (mutexes) required by high priority. At this time, our low priority jobs will be executed before high priority jobs.

Guess you like

Origin blog.csdn.net/qq_45125250/article/details/114906034