見た目はかなり悪いが、、、thread::spawnで同時にスレッドを走らせることができる。
各スレッドでは全てループ処理で待ち受けておいて、目的を達成したらbreakする。
static Washer_queue: Mutex<VecDeque<u32>> = Mutex::new(VecDeque::new());
static Dryer_queue: Mutex<VecDeque<u32>> = Mutex::new(VecDeque::new());
static Folder_queue: Mutex<VecDeque<u32>> = Mutex::new(VecDeque::new());
static Done_queue: Mutex<VecDeque<u32>> = Mutex::new(VecDeque::new());
fn assemble_laundry(n: u32) {
for i in 1..(n+1) {
Washer_queue.lock().unwrap().push_back(i);
}
}
fn washer() {
let w = Washer_queue.lock().unwrap().pop_front();
if w != None {
println!("washing {:?}...", w.unwrap());
thread::sleep(Duration::from_millis(300));
Dryer_queue.lock().unwrap().push_back(w.unwrap());
}
}
fn dryer() {
let d = Dryer_queue.lock().unwrap().pop_front();
if d != None {
println!("Drying {:?}...", d.unwrap());
thread::sleep(Duration::from_millis(200));
Folder_queue.lock().unwrap().push_back(d.unwrap());
}
}
fn folder() {
let f = Folder_queue.lock().unwrap().pop_front();
if f != None {
println!("Folding {:?}...", f.unwrap());
thread::sleep(Duration::from_millis(100));
Done_queue.lock().unwrap().push_back(f.unwrap());
}
}
fn main() {
assemble_laundry(4);
println!("{:?}", Washer_queue);
let wash_handle = thread::spawn(|| {
loop {
if Washer_queue.lock().unwrap().len() == 0 {
break;
}
washer();
}
});
let dry_handle = thread::spawn(|| {
loop {
if Done_queue.lock().unwrap().len() == 4 {
break;
}
dryer();
}
});
let fold_handle = thread::spawn(|| {
loop {
if Done_queue.lock().unwrap().len() == 4{
break;
}
folder();
}
});
wash_handle.join().unwrap();
dry_handle.join().unwrap();
fold_handle.join().unwrap();
println!("Washer {:?}", Washer_queue);
println!("Dryer {:?}", Dryer_queue);
println!("Folder {:?}", Folder_queue);
println!("All work finished");
}
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.20s
Running `target/debug/parallel`
Mutex { data: [1, 2, 3, 4], poisoned: false, .. }
washing 1…
washing 2…
Drying 1…
Folding 1…
washing 3…
Drying 2…
Folding 2…
washing 4…
Drying 3…
Folding 3…
Drying 4…
Folding 4…
Mutex { data: [], poisoned: false, .. }
Mutex { data: [], poisoned: false, .. }
Mutex { data: [], poisoned: false, .. }
All work finished
もうちょっとうまい書き方をしたいが、やりたいこと自体はできている。。