Rust笔记 - Condvar条件变量

1,704 阅读1分钟

条件变量是线程间同步的重要工具,能够使线程间通过触发(通知)的方式进行通讯,而不是轮询的方式。大大提高cpu使用率,降低轮询到来的性能(轮询频率低,造成通知不及时,能明显感受到卡顿;轮询频率过高又会造成大量无效的询问)。在Linux C 上编程,条件变量是很重要的线程同步工具,但Rust本书支持 mpsc::channel 线程间通讯工具。能够实现大部分条件变量适用的场景,导致条件变量同步工具很容易被忽略。下面看一下Rust 条件变量的使用方法吧。


Rust 实例:

fn main() {
    let flag = std::sync::Arc::new(std::sync::Mutex::new(false));
    let cond = std::sync::Arc::new(std::sync::Condvar::new());
    let cflag = flag.clone();
    let ccond = cond.clone();

    let hdl = std::thread::spawn(move || {
        let mut m = { *cflag.lock().unwrap() };
        let mut counter = 0;

        while counter < 3 {
            while !m {
                m = *ccond.wait(cflag.lock().unwrap()).unwrap();
            }

            {
                m = false;
                *cflag.lock().unwrap() = false;
            }

            counter += 1;
            println!("inner counter: {}", counter);
        }
    });

    let mut counter = 0;
    loop {
        std::thread::sleep(std::time::Duration::from_millis(1000));
        *flag.lock().unwrap() = true;
        counter += 1;
        if counter > 3 {
            break;
        }
        println!("outside counter: {}", counter);
        cond.notify_one();
    }
    hdl.join().unwrap();
    println!("{:?}", flag);
}

实例通过主线程触发子线程实现交替打印信息。

outside counter: 1
inner counter: 1
outside counter: 2
inner counter: 2
outside counter: 3
inner counter: 3