面试题答案
一键面试use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use std::time::Duration;
use rand::Rng;
fn main() {
let (tx, rx): (Sender<i32>, Receiver<i32>) = channel();
// 生产者线程
thread::spawn(move || {
loop {
let num = rand::thread_rng().gen::<i32>();
tx.send(num).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
// 消费者线程
for num in rx {
println!("Received: {}", num);
}
}
- 通道创建:
- 使用
std::sync::mpsc::channel
创建一个通道,tx
是发送端,rx
是接收端。
- 使用
- 生产者线程:
thread::spawn
创建一个新线程,在这个线程中,使用rand::thread_rng().gen::<i32>()
生成一个随机数,然后通过tx.send(num)
将随机数发送到通道中,接着线程休眠1秒。
- 消费者线程:
- 在主线程中,通过
for num in rx
循环接收通道中的数据,并打印出来。这里rx
实现了Iterator
trait,所以可以直接在for
循环中使用。
- 在主线程中,通过
注意,需要在Cargo.toml
文件中添加rand
依赖:
[dependencies]
rand = "0.8.5"