MIT xv6 2020系列实验:Lab7 thread

这次实验的内容比较杂,但是简单。

任务一:Uthread:switching(线程切换)

为thread添加context来保存寄存器上下文:

struct context {
  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;
};

struct thread {
  char       stack[STACK_SIZE]; /* the thread's stack */
  int        state;             /* FREE, RUNNING, RUNNABLE */
  struct context context;
};

thread_create如下,为ra分配调用地址,为sp分配旧栈指针。

void
thread_create(void (*func)())
{
  struct thread *t;

  for (t = all_thread; t < all_thread + MAX_THREAD; t++) {
    if (t->state == FREE) break;
  }
  t->state = RUNNABLE;
  // YOUR CODE HERE
  // user ra return func in switch
  t->context.ra = (uint64)func;
  // point to stack top(highest addr)
  t->context.sp = (uint64)t->stack + STACK_SIZE;
}

在thread_schedule时进行上下文切换:

if (current_thread != next_thread) {         /* switch threads?  */
  next_thread->state = RUNNING;
  t = current_thread;
  current_thread = next_thread;
  /* YOUR CODE HERE
     * Invoke thread_switch to switch from t to next_thread:
     * thread_switch(??, ??);
     */
  thread_switch((uint64)&t->context, (uint64)&current_thread->context);
}

任务二:Using thread(cpp)
这部分是cpp的内容,比较简单,只需要在put操作中加锁就行。

任务三:Barrier(cpp)
所有线程需要在一个点上等待,与锁不同,这次用广播变量pthread_cond_broadcast可以一次性控制变量上的所有锁,相当于控制一个计数锁。

结束。

posted @   Thaudmin  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示