#future #thread #stream #waker #park

suspend

A common mechanism for suspending a thread or a Future until notified

4 releases

0.1.3 Jul 26, 2020
0.1.2 Jul 25, 2020
0.1.1 Jul 25, 2020
0.1.0 Jul 23, 2020

#1361 in Asynchronous

MIT/Apache

32KB
622 lines

suspend

This crate provides various utilities for moving between async and synchronous contexts. It allows for a thread to easily block on a Future or Stream, and provides ways to suspend a Future until it is notified.

Documentation

You can read the docs here, or generate them on your own using cargo doc.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


lib.rs:

This crate provides various utilities for moving between async and synchronous contexts.

Examples

The [Task] structure allows a Future or a polling function to be evaluated in a blocking manner:

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));

Similarly, the [Iter] structure allows a Stream instance to be consumed in an async or blocking manner:

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]);

The [Suspend] structure may be used to coordinate between threads and Futures, allowing either to act as a waiter or notifier:

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 });

Dependencies

~71KB