Preemptive Process Scheduling 的觀念

jollen 發表於 November 2, 2006 2:55 PM

先前我們在介紹 sys_getppid 時,跳掉了一段 code 如下:

#if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
{
   ...
}
#endif

這段 code 在判斷 kernel 是否有 'CONFIG_SMP'(多處理器)與 'CONFIG_PREEMPT'(可搶先的 process 排程)。目前 kernel 2.6 在各種處理器平臺已經支援 preemptive process scheduler,當然也包含了 i386 處理器。

這個 kernel 的設定位於 arch/i386/Kconfig,我們節錄 Kconfig 內容如下:

config PREEMPT
        bool "Preemptible Kernel"
        help
          This option reduces the latency of the kernel when reacting to
          real-time or interactive events by allowing a low priority process to
          be preempted even if it is in kernel mode executing a system call.
          This allows applications to run more reliably even when the system is
          under load.
Say Y here if you are building a kernel for a desktop, embedded or real-time system. Say N if you are unsure.

這段 code 與 CONFIG_PREEMPT 的用意非常清楚:提供 preemptive process scheduling 的能力,我們對 Linux kernel preemptive process scheduling 的處理方法相當感興趣。

在進一步研究與 scheduling 有關的 system call 與 'CONFIG_PREEMPT' 前,有必要先來複習一下什麼是 "preemptvie"。

Preemption

一個重要的工作是了解「preemptive」的觀念。

當 process 進入執行狀態(running state)時,排程器(scheduler)會去檢查進入該 process 優先序(priority),若該 process 的 priority 比目前執行中的 process priority 高,Linux 便會搶先(preemptive)執行該 process,因此原本的 process 便被中斷(interrupt)。

這種 high priority process 把 low priority process 執行權了活生生搶走的機制便是 preemptive process scheduling;因此我們說,Linux 的 process 是 "preemptive"!Preemption(搶奪)的排程,目前在 Linux 2.6 的核心裡已經有不錯的支援了。

更多 Linux Preemptive Scheduling

1. Linux 的 scheduler 包含 preemptive 的實作。
2. Linux kernel 本身是 nonpreemptvie。我們在這裡指的 "preemptive" 是指 "process preemptive"。所以當 process 是在 User Mode 時才能被搶先。
3. Process preemptvie(可被搶先因此中斷):process 除了在 time-slice 用完時被中斷外(典型案例),在某些狀況下也是可以被中斷的。例如,前面提到的優先序問題便是一例。
4. 被中斷的 process 仍然是 running state(因為只是被搶先而已)。

Linux/Unix 作業系統核心是 nonpreemptive 的實作,這樣的作業系統設計較簡單,並且可免除許多核心同步(kernel synchronization)的問題。

Preemptive Scheduling

以下是節錄自作業系統教科書裡,對於可搶先班程的說明[1]:

CPU scheduling decisions may take place when a process -

1. Switches from running to waiting state.
2. Switches from running to ready state.
3. Switches from waiting to ready.
4. Terminates.

Scheduling under 1 and 4 is nonpreemptive.


這裡有一份 preemption 的名詞解釋:http://www.netrino.com/Publications/Glossary/Preemption.html

[1] A. Silberschatz, P. Galvin, and G. Gagne, Applied Operating System Concepts, First Edition, John Wiley & Sons, Inc. (2000).

Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue

您可透過電子郵件 jollen@jollen.org,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw