面试题答案
一键面试代码示例
use std::sync::mpsc;
use std::thread;
fn main() {
// 创建通道
let (tx, rx) = mpsc::channel();
// 克隆发送端,以便在新线程中使用
let tx_clone = tx.clone();
// 启动新线程
thread::spawn(move || {
let message = String::from("Hello, main thread!");
// 发送消息
tx_clone.send(message).unwrap();
});
// 主线程接收消息
let received = rx.recv().unwrap();
println!("Received: {}", received);
}
通道两端工作原理
-
发送端(
Sender
):- 在代码中,
tx
是发送端。通过调用tx.send()
方法,将数据发送到通道中。 send
方法是阻塞的,这意味着如果通道的接收端还没有准备好接收数据,发送端会一直等待,直到接收端准备好。- 可以通过
clone
方法克隆发送端,这样可以在多个线程中使用同一个通道进行发送操作。例如let tx_clone = tx.clone();
。
- 在代码中,
-
接收端(
Receiver
):rx
是接收端。通过调用rx.recv()
方法来接收通道中的数据。recv
方法也是阻塞的,它会等待直到有数据发送到通道中,然后接收并返回该数据。- 除了
recv
之外,还有try_recv
方法,try_recv
是非阻塞的,如果通道中没有数据,它会立即返回Err
。