测试线程创建与切换

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

临时线程入口点:

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. }

8. // src/process/structs.rs
9. impl Thread {
10. pub fn get_boot_thread() -> Box<Thread> {
11. Box::new(Thread {
12. context: Context::null(),
13. kstack: KernelStack::new_empty(),
14. })
15. }
16. }

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

下面正式开始测试:

1. // src/process/mod.rs

3. pub fn init() {

5. let mut boot_thread = Thread::get_boot_thread();
6. let mut temp_thread = Thread::new_kernel(temp_thread as usize);

8. unsafe {
9. // 对于放在堆上的数据,我只想到这种比较蹩脚的办法拿到它所在的地址...
10. temp_thread.append_initial_arguments([&*boot_thread as *const Thread as usize, &*temp_thread as *const Thread as usize, 0]);
11. }
12. boot_thread.switch_to(&mut temp_thread);

14. println!("switched back from temp_thread!");
15. loop {}
16. }

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

内核线程切换与测试

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

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

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