Files
simple-rust-tests/__concurrent/async-fn-resumed-after-completion/src/main.rs
2024-03-09 13:14:31 +08:00

48 lines
1.2 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
async fn action(input: Option<i32>) -> Option<String> {
// 若 input输入是None则返回 None
// 事实上也可以这么写: `let i = input?;`
let _i = match input {
Some(input) => input,
None => return None,
};
// 这里定义一些逻辑
Some("test".into())
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = tokio::sync::mpsc::channel(128);
let mut done = false;
let operation = action(None);
tokio::pin!(operation);
tokio::spawn(async move {
let _ = tx.send(1).await;
let _ = tx.send(3).await;
let _ = tx.send(2).await;
});
loop {
tokio::select! {
res = &mut operation, if !done => {
println!("res = &mut operation, done={}", done);
done = true;
if let Some(v) = res {
println!("GOT = {}", v);
return;
}
}
Some(v) = rx.recv() => {
println!("Some(v={}) = rx.recv()", v);
if v % 2 == 0 {
// `.set` 是 `Pin` 上定义的方法
operation.set(action(Some(v)));
done = false;
}
}
}
}
}