# 基于mykernel的一个简单的时间片轮转多道程序内核

学号265原创作品，转载请注明出处 + <https://github.com/mengning/linuxkernel/>

## 一、单进程内核

在实验楼虚拟机中打开qemu运行单进程内核：

`cd LinuxKernel/linux-3.9.4`\
`rm -rf mykernel`\
`patch -p1 < ../mykernel_for_linux3.9.4sc.patch`\
`make allnoconfig`\
`make`

![](/files/-L_hUBAMWGi8aRg599fa)

`qemu -kernel arch/x86/boot/bzImage`

![](/files/-L_hUb0uEq_MW55-YTlk)

可以看到qemu窗口中不断输出my\_start\_kernel和my\_timer\_handler相关信息。\
现尝试修改mymain.c和myinterrupt.c实现时间片轮转的多道程序。

## 二、时间片轮转多道程序分析

在孟老师的mykernel项目中查看相关文件，主要是mymain.c，myinterrupt.c，mypcb.h这三个文件。\
其中主要的数据结构体定义在mypcb.h文件中：

![mypcb.h](/files/-L_hY2C623o66oLfAsU9)

Tread结构体即线程结构体，拥有ip和sp两个成员变量，ip指向cpu运行地址，sp指向线程的栈顶地址。\
PCB结构体定义了pcb的id、状态、栈、线程、任务入口、指向下一pcb的指针、优先级等成员变量。

而myinterrupt.c的主要函数my\_schedule内容如下：

![myinterrupt.c片段](/files/-L_haI_03IIq7eDUjIuv)

该函数通过嵌入两段汇编代码，实现了从当前进程到下一进程间的切换。\
首先通过get\_next函数，获取最高优先级的pid。\
然后判断的是下一线程是否为就绪态，如果下一进程已就绪，若已就绪则保存现场，将当前线程相关内容入栈，上一线程相关内容出栈，然后切换线程ip；\
若下一线程未就绪，则将其改为就绪态，并直接切换线程为下一线程，然后再进行相关转换。

最后是mymain.c：

![mymain.c片段](/files/-L_hfaWNIS992vzEatuM)

其主要函数my\_start\_kernel首先初始化父进程，然后循环产生子进程，子进程的优先级随机产生；\
同时父进程调用my\_schedule对产生的线程进行调度，从而实现时间片轮转的多道程序。

## 三、实验结果

通过上面的分析可以知道如何实现时间片轮转的多道程序，将上述三个文件拷贝到mykernel中，重新编译，并在qemu运行，实验结果如图：

![](/files/-L_hwjDnxBAGtkBYX8F0)

可以看到进程间的切换，实验成功。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jacklu233.gitbook.io/blog/ji-yu-mykernel-de-yi-ge-jian-dan-de-shi-jian-pian-lun-zhuan-duo-dao-cheng-xu-nei-he.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
