← 中文资源

简体中文版本

Thread Park 与 Unpark 交接

用 thread::park 与 Thread::unpark 在线程间传递信号:不需要 channel,且先到的 unpark 会留下许可,不会丢唤醒。

阅读英文原文

实现说明

Thread Park 与 Unpark 交接可以归结为函数 main。 这个文件只在 while !flag.load(Ordering::Acquire) 里循环。

使用要点

  • 演示输出是带标签的(worker resumed after park、park/unpark handoff complete),每个操作都会留下自己的一行标注。

常见问题

运行「Thread Park 与 Unpark 交接」会打印什么?

整个文件跑完,输出行以 worker resumed after park、park/unpark handoff complete 这类前缀开头。

核心语句

let worker = thread::spawn(move || {
    while !flag.load(Ordering::Acquire) {
        thread::park();
    }
    println!("worker resumed after park");
});
worker.join().unwrap();

代码示例

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;

fn main() {
    let ready = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&ready);

    // an unpark that arrives before park is remembered as a permit
    let worker = thread::spawn(move || {
        while !flag.load(Ordering::Acquire) {
            thread::park();
        }
        println!("worker resumed after park");
    });

    thread::sleep(std::time::Duration::from_millis(20));
    ready.store(true, Ordering::Release);
    worker.thread().unpark();

    worker.join().unwrap();
    println!("park/unpark handoff complete");
}