测试线程创建与切换

我们想做的事情是:新建一个临时线程,从启动线程切换到临时线程,再切换回来。

临时线程入口点:

  1. // src/process/mod.rs
  2. #[no_mangle]
  3. pub extern "C" fn temp_thread(from_thread: &mut Thread, current_thread: &mut Thread) {
  4. println!("I'm leaving soon, but I still want to say: Hello world!");
  5. current_thread.switch_to(from_thread);
  6. }

传入的参数中有一个 from_thread ,它本应代表启动线程。但是身处启动线程中,我们如何构造一个 Thread 实例表示其自身呢?

  1. // src/context.rs
  2. impl Context {
  3. pub fn null() -> Context {
  4. Context { content_addr: 0, }
  5. }
  6. }
  7. // src/process/structs.rs
  8. impl Thread {
  9. pub fn get_boot_thread() -> Box<Thread> {
  10. Box::new(Thread {
  11. context: Context::null(),
  12. kstack: KernelStack::new_empty(),
  13. })
  14. }
  15. }

其实作为一个正在运行的线程,栈早就开好了,我们什么都不用做啦!一切都被我们的线程切换机制搞定了。

下面正式开始测试:

  1. // src/process/mod.rs
  2. pub fn init() {
  3. let mut boot_thread = Thread::get_boot_thread();
  4. let mut temp_thread = Thread::new_kernel(temp_thread as usize);
  5. unsafe {
  6. // 对于放在堆上的数据,我只想到这种比较蹩脚的办法拿到它所在的地址...
  7. temp_thread.append_initial_arguments([&*boot_thread as *const Thread as usize, &*temp_thread as *const Thread as usize, 0]);
  8. }
  9. boot_thread.switch_to(&mut temp_thread);
  10. println!("switched back from temp_thread!");
  11. loop {}
  12. }

终于能够 make run 看一下结果啦!

内核线程切换与测试

  1. I'm leaving soon, but I still want to say: Hello world!
  2. switched back from temp_thread!

可见我们切换到了临时线程,又切换了回来!测试成功!

截至目前所有的代码可以在这里找到以供参考。