Skip to content

Commit

Permalink
runtime: add block_on_all (tokio-rs#398)
Browse files Browse the repository at this point in the history
Signed-off-by: Marc-Antoine Perennou <[email protected]>
  • Loading branch information
Keruspe authored and carllerche committed Jun 15, 2018
1 parent 011ebf4 commit 71c8f56
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,31 @@ impl Runtime {
rx.wait().unwrap()
}

/// Run a future to completion on the Tokio runtime, then wait for all
/// background futures to complete too.
///
/// This runs the given future on the runtime, blocking until it is
/// complete, waiting for background futures to complete, and yielding
/// its resolved result. Any tasks or timers which the future spawns
/// internally will be executed on the runtime and waited for completion.
///
/// This method should not be called from an asynchrounous context.
///
/// # Panics
///
/// This function panics if the executor is at capacity, if the provided
/// future panics, or if called within an asynchronous execution context.
pub fn block_on_all<F, R, E>(mut self, future: F) -> Result<R, E>
where
F: Send + 'static + Future<Item = R, Error = E>,
R: Send + 'static,
E: Send + 'static,
{
let res = self.block_on(future);
self.shutdown_on_idle().wait().unwrap();
res
}

/// Signals the runtime to shutdown once it becomes idle.
///
/// Returns a future that completes once the shutdown operation has
Expand Down
30 changes: 30 additions & 0 deletions tests/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,33 @@ fn spawn_many() {
runtime.shutdown_on_idle().wait().unwrap();
assert_eq!(ITER, *cnt.lock().unwrap());
}

#[test]
fn spawn_from_block_on_all() {
let cnt = Arc::new(Mutex::new(0));
let c = cnt.clone();

let mut runtime = Runtime::new().unwrap();
let msg = runtime
.block_on_all(lazy(move || {
{
let mut x = c.lock().unwrap();
*x = 1 + *x;
}

// Spawn!
tokio::spawn(lazy(move || {
{
let mut x = c.lock().unwrap();
*x = 1 + *x;
}
Ok::<(), ()>(())
}));

Ok::<_, ()>("hello")
}))
.unwrap();

assert_eq!(2, *cnt.lock().unwrap());
assert_eq!(msg, "hello");
}

0 comments on commit 71c8f56

Please sign in to comment.