【Tokio】單次一對一通道
阿新 • • 發佈:2022-03-30
環境
- Time 2022-01-12
- Rust 1.57.0
- Tokio 1.15.0
概念
參考:https://docs.rs/tokio/latest/tokio/sync/oneshot/index.html
oneshot
可以實現單對單的訊息通訊,不過只能通訊一次。
示例
main.rs
一次跨執行緒的通訊。
use std::thread; use tokio::sync::oneshot; #[tokio::main] async fn main() { let (tx, rx) = oneshot::channel(); tokio::spawn(async { println!("{}", thread::current().name().unwrap()); if tx.send("jiangbo").is_err() { println!("the receiver dropped"); } }); match rx.await { Ok(v) => println!("got = {}", v), Err(_) => println!("the sender dropped"), } println!("{}", thread::current().name().unwrap()); }
JoinHandle
如果是任務的最終結果,除了通過訊息通訊,也可以直接獲取。
use std::thread; #[tokio::main] async fn main() { let result = tokio::spawn(async { println!("{}", thread::current().name().unwrap()); "jiangbo" }); match result.await { Ok(v) => println!("got = {}", v), Err(_) => println!("error"), } println!("{}", thread::current().name().unwrap()); }
錯誤
如果沒有傳送任何訊息就刪除了傳送者,接收者會異常。
use std::thread; use tokio::sync::oneshot; #[tokio::main] async fn main() { let (tx, rx) = oneshot::channel::<i32>(); tokio::spawn(async { println!("{}", thread::current().name().unwrap()); drop(tx); }); match rx.await { Ok(_) => unreachable!(), Err(_) => println!("the sender dropped"), } println!("{}", thread::current().name().unwrap()); }
總結
oneshot
用來實現一次單對單的通訊,可以跨執行緒。