我对于《Rust by Example》中的通道章节的输出感到相当困惑:
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;
static NTHREADS: i32 = 3;
fn main() {
// Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
// where `T` is the type of the message to be transferred
// (type annotation is superfluous)
let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();
for id in 0..NTHREADS {
// The sender endpoint can be copied
let thread_tx = tx.clone();
// Each thread will send its id via the channel
thread::spawn(move || {
// The thread takes ownership over `thread_tx`
// Each thread queues a message in the channel
thread_tx.send(id).unwrap();
// Sending is a non-blocking operation, the thread will continue
// immediately after sending its message
println!("thread {} finished", id);
});
}
// Here, all the messages are collected
let mut ids = Vec::with_capacity(NTHREADS as usize);
for _ in 0..NTHREADS {
// The `recv` method picks a message from the channel
// `recv` will block the current thread if there no messages available
ids.push(rx.recv());
}
// Show the order in which the messages were sent
println!("{:?}", ids);
}
使用默认的NTHREADS = 3
,我得到了以下输出:
thread 2 finished
thread 1 finished
[Ok(2), Ok(1), Ok(0)]
for
循环中的println!("thread {} finished", id);
为什么会以相反的顺序打印?thread 0 finished
去哪了?
当我将NTHREADS = 8
更改后,发生了更神秘的事情:
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)]
打印顺序让我更加困惑,而且线程0总是缺失的。如何解释这个例子?
我在不同的电脑上尝试了这个例子,结果都一样。