< 返回版块

Zac.R 发表于 2019-11-17 19:31

Tags:谁来讲解下Condvar?

use std::sync::{Arc, Mutex, Condvar};
use std::thread;
use std::time::Duration;

fn main() {
    println!("Hello, world!");
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair2 = pair.clone();

    thread::spawn(move || {
        thread::sleep(Duration::from_secs(1));
        let &(ref lock, ref cvar) = &*pair2;
        let mut started = lock.lock().unwrap();
        *started = true;
        cvar.notify_one();
        println!("child thread {}", *started);
    });

    let &(ref lock, ref cvar) = &*pair;
    let mut started = lock.lock().unwrap();

    println!("before wait {}", *started);
    while !*started {
        started = cvar.wait(started).unwrap();
    }
    println!("after wait {}", *started);
}

评论区

写评论
祐祐 2021-07-30 21:11

我改成這樣,應該對你會有用...

#![allow(unused)]
use std::sync::{Arc, Mutex, Condvar};
use std::thread;
use std::time::Duration;

fn main() {
    let pair = Arc::new((Mutex::new(4), Condvar::new()));
    let pair2 = pair.clone();

    let thread1 = thread::spawn(move || {
        let &(ref lock, ref cvar) = &*pair2;
        for i in 0..4{
            thread::sleep(Duration::from_secs(1));
            let mut started = lock.lock().unwrap();
            *started -= 1;
            println!("...");
            cvar.notify_one();
            println!("child thread - value:{}", *started);
        }
    });
    
    let &(ref lock, ref cvar) = &*pair;
    {
        let mut started = lock.lock().unwrap();
        println!("before wait {}", *started);
        while *started > 2 {
            println!("-");
            started = cvar.wait(started).unwrap();
            println!("+");
        }
        println!("after wait {}", *started);
    }
    thread1.join();
}
shaitao 2020-02-20 17:15

为什么要用Condvar 为什么要和锁一起用 [/黑脸]

对以下内容的回复:

Ryan-Git 2019-11-17 22:48

讲啥?条件变量不都是这样用的

1 共 3 条评论, 1 页