gpt4 book ai didi

multithreading - 了解 Rust channel 。 `send` 如何工作?

转载 作者:行者123 更新时间:2023-12-03 11:43:12 24 4
gpt4 key购买 nike

我正在阅读 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com