6.S081 Xv6 Lab: Multithreading
Lab: Multithreading of MIT 6.S081 Fall 2020
$ git fetch
$ git checkout thread
$ make clean
Uthread: switching between threads
这个题有意思的,手写用户线程的实现。做起来不难,大体框架人家都给了,自己只要实现一下上下文切换。
首先在 notxv6/uthread.c
里面补充定义一个「线程上下文」:
// saved registers for thread context switches
struct threadcontext {
uint64 ra;
uint64 sp;
// callee-saved
uint64 s0;
uint64 s1;
uint64 s2;
uint64 s3;
uint64 s4;
uint64 s5;
uint64 s6;
uint64 s7;
uint64 s8;
uint64 s9;
uint64 s10;
uint64 s11;
};
这个其实和 kernel/proc.h
里面的 struct context
是一样的,直接导进来用也行。
接下来在 notxv6/uthread_switch.S
中实现上下文的切换,直接抄 kernel/swtch.S
:
.text
/* void
thread_switch(struct threadcontext *old, struct threadcontext *new);
* save the old thread's registers,
* restore the new thread's registers.
*/
.globl thread_switch
thread_switch:
sd ra, 0(a0)
sd sp, 8(a0)
sd s0, 16(a0)
sd s1, 24(a0)
sd s2, 32(a0)
sd s3, 40(a0)
sd s4, 48(a0)
sd s5, 56(a0)
sd s6, 64(a0)
sd s7, 72(a0)
sd s8, 80(a0)
sd s9, 88(a0)
sd s10, 96(a0)
sd s11, 104(a0)
ld ra, 0(a1)
ld sp, 8(a1)
ld s0, 16(a1)
ld s1, 24(a1)
ld s2, 32(a1)
ld s3, 40(a1)
ld s4, 48(a1)
ld s5, 56(a1)
ld s6, 64(a1)
ld s7, 72(a1)
ld s8, 80(a1)
ld s9, 88(a1)
ld s10, 96(a1)
ld s11, 104(a1)
ret /* return to ra */
接下来就用上下文、上下文切换来完成线程的切换。
在 struct thread
的定义里面加上一项 context:
struct thread {
...
struct threadcontext context; /* switch here to run thread */
};
新建线程的时候要设置一下相关的 context:
ra
寄存器指向线程要运行的函数,switch 结束后会返回到 ra 处开始运行;sp
指向线程自己的栈。要注意:压栈是减小栈指针,所以一开始在最高处。(参考 CSAPP2e 3.4.2 fig 3-5)
void
thread_create(void (*func)())
{
struct thread *t;
for