forループが終わってからスレッドが並列で動いているので、rustとpythonだと、スレッドの立ち方が微妙に違いますね。
static SIZE: u32 = 5; static Shared_Memory: Mutex<Vec<i32>> = Mutex::new(Vec::new()); fn main() { for _i in 0..SIZE { Shared_Memory.lock().unwrap().push(-1); } consumer(); producer(); println!("{:?}", Shared_Memory); } fn producer() { let name = "Producer".to_string(); let mut memory = Shared_Memory.lock().unwrap(); for i in 0..SIZE { println!("{}: Writing {}", name, i); memory[i as usize] = i as i32; } } fn consumer() { let name = "Consumer".to_string(); let handle = thread::spawn(move || { let mut memory = Shared_Memory.lock().unwrap(); for i in 0..SIZE { while true { let line = memory[i as usize]; if line == -1{ println!("{}: Data not available, sleeping fro 1 second for retrying.", name); thread::sleep(Duration::from_millis(500)); } println!("{}: Read: ({})", name, line); break; } } }); handle.join().unwrap(); }
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.33s
Running `target/debug/parallel`
Consumer: Data not available, sleeping fro 1 second for retrying.
Consumer: Read: (-1)
Consumer: Data not available, sleeping fro 1 second for retrying.
Consumer: Read: (-1)
Consumer: Data not available, sleeping fro 1 second for retrying.
Consumer: Read: (-1)
Consumer: Data not available, sleeping fro 1 second for retrying.
Consumer: Read: (-1)
Consumer: Data not available, sleeping fro 1 second for retrying.
Consumer: Read: (-1)
Producer: Writing 0
Producer: Writing 1
Producer: Writing 2
Producer: Writing 3
Producer: Writing 4
Mutex { data: [0, 1, 2, 3, 4], poisoned: false, .. }