main.rs:use std::sync::mpsc; // 引入 mpsc 库,用于实现通道通信use std::thread; // 引入 thread 库,用于模拟耗时操作use std::time::Duration; // 引入 Duration 类型,用于模拟耗时操作的时间async fn producer(tx: mpsc::Sender) { // 定义生产者函数,它接受一个通道发送器 for i in 0..10 { // 生产者循环发送 0 到 9 的数字 thread::sleep(Duration::from_millis(500)); // 模拟耗时操作 tx.send(i).unwrap(); // 将数字发送到通道中 }}async fn consumer(rx: mpsc::Receiver) { // 定义消费者函数,它接受一个通道接收器 loop { match rx.recv() { // 消费者循环接收通道中的数据 Ok(i) => println!("Received {}", i), // 如果接收成功,打印接收到的数字 Err(_) => break, // 如果接收失败,跳出循环
...
继续阅读
(30)