Skip to content

add Executor::run_with_local #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
49 changes: 49 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,55 @@ impl Executor {
}
})
}

/// Runs a local executor and the multi-threaded one until the given future completes.
///
/// # Examples
///
/// ```
/// use async_executor::{Executor, Task};
///
/// let ex = Executor::new();
///
/// let task = ex.spawn(async { 1 + 2 });
/// let res = ex.run_with_local(async {
/// let local = Task::local(async { 1 + 1 });
/// task.await * local.await
/// });
///
/// assert_eq!(res, 6);
/// ```
pub fn run_with_local<T>(&self, future: impl Future<Output = T>) -> T {
let local_executor = LocalExecutor::new();
LOCAL_EX.set(&local_executor, || {
self.enter(|| {
let (p, u) = parking::pair();

let ticker = self.ex.ticker({
let u = u.clone();
move || u.unpark()
});

pin!(future);
let waker = waker_fn(move || u.unpark());
let cx = &mut Context::from_waker(&waker);

'start: loop {
if let Poll::Ready(t) = future.as_mut().poll(cx) {
break t;
}

for _ in 0..200 {
if !local_executor.ex.tick() && !ticker.tick() {
p.park();
continue 'start;
}
}
p.park_timeout(Duration::from_secs(0));
}
})
})
}
}

impl Default for Executor {
Expand Down