异步通道
有些 crate 支持使用异步通道。例如 tokio
:
use tokio::sync::mpsc; async fn ping_handler(mut input: mpsc::Receiver<()>) { let mut count: usize = 0; while let Some(_) = input.recv().await { count += 1; println!("Received {count} pings so far."); } println!("ping_handler complete"); } #[tokio::main] async fn main() { let (sender, receiver) = mpsc::channel(32); let ping_handler_task = tokio::spawn(ping_handler(receiver)); for i in 0..10 { sender.send(()).await.expect("Failed to send ping."); println!("Sent {} pings so far.", i + 1); } drop(sender); ping_handler_task.await.expect("Something went wrong in ping handler task."); }
-
将通道大小更改为
3
,然后看看对操作执行会有什么影响。 -
Overall, the interface is similar to the
sync
channels as seen in the morning class. -
尝试移除
std::mem::drop
调用。会出现什么情况?这是为什么? -
Flume crate 包含可以同时实现
sync
、async
send
和recv
的渠道,为涉及 IO 和大量 CPU 处理任务的复杂应用提供了极大便利。 -
使用
async
通道的优势在于,我们能够将它们与其他future
结合起来,从而创建复杂的控制流。