我正在阅读 this 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();
let mut children = Vec::new();
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
let child = 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);
});
children.push(child);
}
// 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 are no messages available
ids.push(rx.recv());
}
// Wait for the threads to complete any remaining work
for child in children {
child.join().expect("oops! the child thread panicked");
}
// Show the order in which the messages were sent
println!("{:?}", ids);
}
我对这两行有问题:
thread_tx.send(id).unwrap();
println!("thread {} finished", id);
怎么样
send
工作?它发送副本?这是我仍然可以使用 id
的唯一方法在 send
中使用后,不是吗?如果我是正确的,那么如何以非复制模式发送?我可以以“自己的方式”发送,即发送功能现在拥有它,但我无法再次使用它。我也可以借用的方式发送,作为引用,但除非另一个线程释放它,否则我无法再次使用它。
最佳答案
How does send work? It sends a copy? That's the only way I can still use id after using it in send, isn't it?
发送发送你给它的任何东西。这里它发送一个副本,因为
id
是 i32,即 Copy
,但它本质上并不关心,The documentation of the Copy trait has some explanations .还有this old answer它提供了一个较短(但不那么广泛)的解释。
关于multithreading - 了解 Rust channel 。 `send` 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61722990/