I'm quite confused by the output of the Rust channel head using an example :
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;
static NTHREADS: i32 = 3;
fn main() {
let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
for id in 0..NTHREADS {
let thread_tx = tx.clone();
thread::spawn(move || {
thread_tx.send(id).unwrap();
println!("thread {} finished", id);
});
}
let mut ids = Vec::with_capacity(NTHREADS as usize);
for _ in 0..NTHREADS {
ids.push(rx.recv());
}
println!("{:?}", ids);
}
By default, NTHREADS = 3I got the following output:
thread 2 finished
thread 1 finished
[Ok(2), Ok(1), Ok(0)]
Why is the loop println!("thread {} finished", id);in the loop forprinted in reverse order? And where is it going thread 0 finished?
When I changed to NTHREADS = 8, something more mysterious happened:
thread 6 finished
thread 7 finished
thread 8 finished
thread 9 finished
thread 5 finished
thread 4 finished
thread 3 finished
thread 2 finished
thread 1 finished
[Ok(6), Ok(7), Ok(8), Ok(9), Ok(5), Ok(4), Ok(3), Ok(2), Ok(1), Ok(0)]
The print order confused me even more, and thread 0 is always absent. How to explain this example?
I tried this on different computers and got the same results.