본문 바로가기

Tech

[concurrency] 조건변수

어떤 조건을 만족하지 않을 때는 프로세스를 대기 상태로 두고,
조건이 만족되면 대기중인 프로세스를
실행하고 싶을 때가 있을 것이다. 
use std::sync::{Arc, Mutex, Condvar};
use std::thread;

fn child(id: u64, p: Arc<(Mutex<bool>, Condvar)>) {
    let (lock, cvar) = &*p;
    let mut started = lock.lock().unwrap();
    while !*started {
        started = cvar.wait(started).unwrap();
	//https://doc.rust-lang.org/std/sync/struct.Condvar.html
    }
    println!("Child {}", id);
}

fn parent(p: Arc<(Mutex<bool>, Condvar)>) {
    let (lock, cvar) = &*p;
    let mut started = lock.lock().unwrap();
    *started = true;
    cvar.notify_all();
    println!("parent");
}


fn main() {
    let pair0 = Arc::new((Mutex::new(false), Condvar::new()));
    let pair1 = pair0.clone();
    let pair2 = pair0.clone();

    let t1 = thread::spawn(move || { child(1, pair1)});
    let t2 = thread::spawn(move || { child(2, pair2)});
    let t0 = thread::spawn(move || { parent(pair0) });

    t0.join().unwrap();
    t1.join().unwrap();
    t2.join().unwrap();
}