#thread #future #stream #park #waker

suspend

挂起线程或Future直到被通知的通用机制

4个版本

0.1.3 2020年7月26日
0.1.2 2020年7月25日
0.1.1 2020年7月25日
0.1.0 2020年7月23日

#1343异步

Download history 3/week @ 2024-03-08 4/week @ 2024-03-29 102/week @ 2024-06-07 10/week @ 2024-06-14

112 每月下载量

MIT/Apache

32KB
622

suspend

此crate提供各种在异步和同步上下文之间切换的实用工具。它允许线程轻松地在Future或Stream上阻塞,并提供挂起Future直到它被通知的方法。

文档

您可以在此处阅读文档,或者使用cargo doc自行生成。

许可证

许可协议为以下之一

由您选择。

贡献

除非您明确说明,否则任何有意提交以包含在作品中的贡献,根据Apache-2.0许可证定义,应按上述方式双许可,不附加任何额外条款或条件。


lib.rs:

此crate提供各种在异步和同步上下文之间切换的实用工具。

示例

结构[Task]允许以阻塞方式评估Future或轮询函数

use suspend::Task;
use std::time::Duration;

let task = Task::from_future(async { 100 }).map(|val| val * 2);
assert_eq!(task.wait_timeout(Duration::from_secs(1)), Ok(200));

同样,结构[Iter]允许以异步或阻塞方式消耗Stream实例

use suspend::{Iter, block_on};

let mut values = Iter::from_iterator(1..);
assert_eq!(block_on(async { values.next().await }), Some(1));
assert_eq!(values.take(3).collect::<Vec<_>>(), vec![2, 3, 4]);

结构[Suspend]可以用于在线程和Future之间协调,允许任一方充当等待者或通知者

use std::time::Duration;
use suspend::{Suspend, block_on};

let mut susp = Suspend::new();
let notifier = susp.notifier();

// start listening for notifications
let mut listener = susp.listen();
// send a notification (satisfies the current listener)
notifier.notify();
// wait for notification (already sent) with a timeout
assert_eq!(listener.wait_timeout(Duration::from_secs(1)), true);
drop(listener);

let mut listener = susp.listen();
notifier.notify();
// the listener is also a Future
block_on(async { listener.await });

依赖项

~70KB