1 个不稳定版本
0.1.0 | 2020年11月20日 |
---|
#19 in #raii
6KB
107 行代码(不含注释)
flo-task
异步任务工具。
SpawnScope
RAII 保护器,用于通知子任务父任务已被丢弃。一个用例是实现一组子任务的优雅关闭。
#[tokio::test]
async fn test_initial_value() {
use std::future::Future;
use std::time::Duration;
use tokio::time::delay_for;
let scope = SpawnScope::new();
fn get_task(mut scope: SpawnScopeHandle) -> impl Future<Output = i32> {
async move {
let mut n = 0;
loop {
tokio::select! {
_ = scope.left() => {
return n
}
_ = delay_for(Duration::from_millis(50)) => {
n = n + 1
}
}
}
}
}
let t1 = tokio::spawn(get_task(scope.handle()));
let t2 = tokio::spawn(get_task(scope.handle()));
let t3 = tokio::spawn(get_task(scope.handle()));
delay_for(Duration::from_millis(100)).await;
drop(scope);
let (v1, v2, v3) = tokio::try_join!(t1, t2, t3).unwrap();
assert!(v1 > 0);
assert!(v2 > 0);
assert!(v3 > 0);
}
依赖项
~5MB
~84K SLoC