Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,32 @@ pub fn block_on<T>(future: impl Future<Output = T>) -> T {
})
}

/// Processes any pending I/O events without blocking.
///
/// This function is intended to be called periodically from synchronous code that needs to
/// drive `async-io` reactor without using [`block_on()`]. If another thread is currently
/// driving the reactor, this function returns immediately without doing any work.
///
/// # Examples
///
/// ```
/// // Periodically yield to async-io tasks from synchronous code.
/// for _ in 0..10 {
/// // ... do some synchronous work ...
/// async_io::yield_now();
/// }
/// ```
pub fn yield_now() {
#[cfg(feature = "tracing")]
let span = tracing::trace_span!("async_io::yield_now");
#[cfg(feature = "tracing")]
let _enter = span.enter();

if let Some(mut reactor_lock) = Reactor::get().try_lock() {
reactor_lock.react(Some(Duration::from_secs(0))).ok();
}
}

/// Runs a closure when dropped.
struct CallOnDrop<F: Fn()>(F);

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ mod reactor;

pub mod os;

pub use driver::block_on;
pub use driver::{block_on, yield_now};
pub use reactor::{Readable, ReadableOwned, Writable, WritableOwned};

/// A future or stream that emits timed events.
Expand Down
32 changes: 32 additions & 0 deletions tests/yield_now.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use async_io::{yield_now, Timer};
use std::time::{Duration, Instant};

#[test]
fn yield_now_returns_without_blocking() {
let start = Instant::now();
for _ in 0..10 {
yield_now();
}
assert!(start.elapsed() < Duration::from_secs(1));
}

#[test]
fn yield_now_drives_timer() {
let start = Instant::now();
let timer = Timer::after(Duration::from_millis(50));
futures_lite::pin!(timer);

let waker = futures_lite::future::block_on(async { std::task::Waker::noop().clone() });
let mut cx = std::task::Context::from_waker(&waker);

use std::future::Future;
while timer.as_mut().poll(&mut cx).is_pending() {
if start.elapsed() > Duration::from_secs(5) {
panic!("timer never fired");
}
yield_now();
std::thread::sleep(Duration::from_millis(5));
}

assert!(start.elapsed() >= Duration::from_millis(50));
}
Loading