上下文切换

虽然上下文切换,这个名词经常听,但是还有有必要重温和加强理解一下。

英文解释

A context switch occurs when a computer’s CPU switches from one process or thread to a different process or thread.

Context switching allows for one CPU to handle numerous processes or threads without the need for additional processors. Any operating system that allows for multitasking relies heavily on the use of context switching to allow different processes to run at the same time. There are three situations that a context switch is necessary, as shown below.

  • Multitasking – When the CPU needs to switch processes in and out of memory, so that more than one process can be running.
  • Kernel/User Switch – When switching between user mode to kernel mode, it may be used (but isn’t always necessary).
  • Interrupts – When the CPU is interrupted to return data from a disk read.

中文解释

1.什么是CPU上下文

以Linux为例,Linux 是一个多任务操作系统,它支持远大于 CPU 数量的任务同时运行。当然,这些任务实际上并不是真的在同时运行,而是因为系统在很短的时间内,将 CPU 轮流分配给它们,造成多任务同时运行的错觉。

而在每个任务运行前,CPU 都需要知道任务从哪里加载、又从哪里开始运行,也就是说,需要系统事先帮它设置好 CPU 寄存器和程序计数器(Program Counter,PC)。

CPU 寄存器,是 CPU 内置的容量小、但速度极快的内存。而程序计数器,则是用来存储 CPU 正在执行的指令位置、或者即将执行的下一条指令位置。它们都是 CPU 在运行任何任务前,必须的依赖环境,因此也被叫做 CPU 上下文。

而这些保存下来的上下文,会存储在系统内核中,并在任务重新调度执行时再次加载进来。这样就能保证任务原来的状态不受影响,让任务看起来还是连续运行。

根据任务的不同,CPU的上下文切换可以分为不同的场景,也就是进程上下文切换、线程上下文切换、中断上下文切换。

2.上下文切换的含义

在单个处理器的时期,操作系统就能处理多线程并发任务。处理器给每个线程分配 CPU 时间片(Time Slice),线程在分配获得的时间片内执行任务。

CPU 时间片是 CPU 分配给每个线程执行的时间段,一般为几十毫秒。在这么短的时间内线程互相切换,我们根本感觉不到,所以看上去就好像是同时进行的一样。

时间片决定了一个线程可以连续占用处理器运行的时长。当一个线程的时间片用完了,或者因自身原因被迫暂停运行了,这个时候,另外一个线程(可以是同一个线程或者其它进程的线程)就会被操作系统选中,来占用处理器。这种一个线程被暂停剥夺使用权,另外一个线程被选中开始或者继续运行的过程就叫做上下文切换(Context Switch)。

参考资料:
1. http://www.linfo.org/context_switch.html
2. https://www.cnblogs.com/winclpt/articles/10873024.html

(完)

发表评论

邮箱地址不会被公开。 必填项已用*标注