6.S081 Xv6 Lab Multithreading

这篇博客详细介绍了MIT 6.S081课程中关于Xv6 Lab的多线程实现,包括Uthread的上下文切换,线程的使用以及线程同步的Barriers。作者展示了如何在Xv6中实现用户线程,使用pthread库实现线程安全的哈希表,并讨论了pthread的条件等待在实现Barrier中的应用。博客以实验结果的满分截图作为结尾。
摘要由CSDN通过智能技术生成

Meaning Unknown's Head Image

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 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值