【发布时间】:2021-08-22 10:44:49
【问题描述】:
尽管查阅了文档,但我仍然无法理解这一行:swtch(&c->scheduler, &p->context);。
我的问题:我知道这行是切换p->context,包括保存寄存器和恢复寄存器,但是我看不懂pc这个过程的变化,那这段代码的执行顺序是什么? swtch(&c->scheduler, &p->context);执行后,是不是马上执行c->proc = 0;,那么执行c->proc=p; 的效果就消失了?我现在很困惑。
代码链接:https://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/proc.c 第 456 行
*// Per-CPU process scheduler.*
*// Each CPU calls scheduler() after setting itself up.*
*// Scheduler never returns. It loops, doing:*
*// - choose a process to run.*
*// - swtch to start running that process.*
*// - eventually that process transfers control*
*// via swtch back to the scheduler.*
void
scheduler(void)
{
struct proc *p;
struct cpu *c = mycpu();
c->proc = 0;
for(;;){
*// Avoid deadlock by ensuring that devices can interrupt.*
intr_on();
int found = 0;
for(p = proc; p < &proc[NPROC]; p++) {
acquire(&p->lock);
if(p->state == RUNNABLE) {
*// Switch to chosen process. It is the process's job*
*// to release its lock and then reacquire it*
*// before jumping back to us.*
p->state = RUNNING;
c->proc = p;
swtch(&c->scheduler, &p->context);
*// Process is done running for now.*
*// It should have changed its p->state before coming back.*
c->proc = 0;
found = 1;
}
release(&p->lock);
}
if(found == 0){
intr_on();
asm volatile("wfi");
}
}
}
【问题讨论】:
-
我认为这只是一个糟糕的代码而已。
-
注意swtch.S,忘记标注了。
-
你有什么不明白的?
-
@Rchar 看这里,我没时间去搜你看不懂的代码。
-
这是上下文切换。它调用的函数使用这些参数继续在其他地方运行,在不同的地址和不同的加载寄存器集。这(非常)大致是任何操作系统如何更改当前执行的上下文。
标签: c operating-system riscv xv6