Get rid of Enter for with_default (#1315)

We want executors to enforce that there are never multiple active at the
same time. This is ensured through `Enter`, which will panic if you
attempt to create more than one. However, by requiring you to pass an
`&mut Enter` to `executor::with_default`, we were *also* disallowing
temporarily overriding the current executor.

This patch removes that requirement.
This commit is contained in:
Jon Gjengset
2019-07-16 14:29:35 -04:00
committed by GitHub
parent 6d186fe40e
commit 003b4d8074
10 changed files with 49 additions and 77 deletions
+14 -21
View File
@@ -41,7 +41,7 @@ use std::task::{Context, Poll, Waker};
use std::thread;
use std::time::{Duration, Instant};
use tokio_executor::park::{Park, ParkThread, Unpark};
use tokio_executor::{Enter, SpawnError};
use tokio_executor::SpawnError;
/// Executes tasks on the current thread
pub struct CurrentThread<P: Park = ParkThread> {
@@ -96,7 +96,6 @@ impl Turn {
/// A `CurrentThread` instance bound to a supplied execution context.
pub struct Entered<'a, P: Park> {
executor: &'a mut CurrentThread<P>,
enter: &'a mut Enter,
}
/// Error returned by the `run` function.
@@ -322,38 +321,35 @@ impl<P: Park> CurrentThread<P> {
where
F: Future,
{
let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter(&mut enter).block_on(future)
let _enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter().block_on(future)
}
/// Run the executor to completion, blocking the thread until **all**
/// spawned futures have completed.
pub fn run(&mut self) -> Result<(), RunError> {
let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter(&mut enter).run()
let _enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter().run()
}
/// Run the executor to completion, blocking the thread until all
/// spawned futures have completed **or** `duration` time has elapsed.
pub fn run_timeout(&mut self, duration: Duration) -> Result<(), RunTimeoutError> {
let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter(&mut enter).run_timeout(duration)
let _enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter().run_timeout(duration)
}
/// Perform a single iteration of the event loop.
///
/// This function blocks the current thread even if the executor is idle.
pub fn turn(&mut self, duration: Option<Duration>) -> Result<Turn, TurnError> {
let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter(&mut enter).turn(duration)
let _enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`");
self.enter().turn(duration)
}
/// Bind `CurrentThread` instance with an execution context.
pub fn enter<'a>(&'a mut self, enter: &'a mut Enter) -> Entered<'a, P> {
Entered {
executor: self,
enter,
}
fn enter<'a>(&'a mut self) -> Entered<'a, P> {
Entered { executor: self }
}
/// Returns a reference to the underlying `Park` instance.
@@ -478,7 +474,7 @@ impl<'a, P: Park> Entered<'a, P> {
let res = self
.executor
.borrow()
.enter(self.enter, || future.as_mut().poll(&mut cx));
.enter(|| future.as_mut().poll(&mut cx));
match res {
Poll::Ready(e) => return e,
@@ -595,9 +591,7 @@ impl<'a, P: Park> Entered<'a, P> {
}
// After any pending futures were scheduled, do the actual tick
borrow
.scheduler
.tick(borrow.id, &mut *self.enter, borrow.num_futures)
borrow.scheduler.tick(borrow.id, borrow.num_futures)
}
}
@@ -605,7 +599,6 @@ impl<'a, P: Park> fmt::Debug for Entered<'a, P> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Entered")
.field("executor", &self.executor)
.field("enter", &self.enter)
.finish()
}
}
@@ -748,7 +741,7 @@ where
// ===== impl Borrow =====
impl<'a, U: Unpark> Borrow<'a, U> {
fn enter<F, R>(&mut self, _: &mut Enter, f: F) -> R
fn enter<F, R>(&mut self, f: F) -> R
where
F: FnOnce() -> R,
{
+3 -7
View File
@@ -12,7 +12,6 @@ use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
use std::thread;
use std::usize;
use tokio_executor::park::Unpark;
use tokio_executor::Enter;
/// A generic task-aware scheduler.
///
@@ -199,7 +198,7 @@ where
///
/// This function should be called whenever the caller is notified via a
/// wakeup.
pub fn tick(&mut self, eid: u64, enter: &mut Enter, num_futures: &AtomicUsize) -> bool {
pub fn tick(&mut self, eid: u64, num_futures: &AtomicUsize) -> bool {
let mut ret = false;
let tick = self.inner.tick_num.fetch_add(1, SeqCst).wrapping_add(1);
@@ -251,14 +250,13 @@ where
//
struct Bomb<'a, U: Unpark> {
borrow: &'a mut Borrow<'a, U>,
enter: &'a mut Enter,
node: Option<Arc<Node<U>>>,
}
impl<'a, U: Unpark> Drop for Bomb<'a, U> {
fn drop(&mut self) {
if let Some(node) = self.node.take() {
self.borrow.enter(self.enter, || release_node(node))
self.borrow.enter(|| release_node(node))
}
}
}
@@ -273,7 +271,6 @@ where
let mut bomb = Bomb {
node: Some(node),
enter: enter,
borrow: &mut borrow,
};
@@ -308,7 +305,6 @@ where
// the internal allocation, appropriately accessing fields and
// deallocating the node if need be.
let borrow = &mut *bomb.borrow;
let enter = &mut *bomb.enter;
let mut scheduled = Scheduled {
task: item,
@@ -316,7 +312,7 @@ where
done: &mut done,
};
if borrow.enter(enter, || scheduled.tick()) {
if borrow.enter(|| scheduled.tick()) {
// we have a borrow of the Runtime, so we know it's not shut down
borrow.num_futures.fetch_sub(2, SeqCst);
}
+12 -20
View File
@@ -1,4 +1,4 @@
use super::{Enter, Executor, SpawnError};
use super::{Executor, SpawnError};
use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
@@ -141,33 +141,27 @@ where
/// Set the default executor for the duration of the closure
///
/// # Panics
///
/// This function panics if there already is a default executor set.
pub fn with_default<T, F, R>(executor: &mut T, enter: &mut Enter, f: F) -> R
/// If a default executor is already set, it will be restored when the closure returns or if it
/// panics.
pub fn with_default<T, F, R>(executor: &mut T, f: F) -> R
where
T: Executor,
F: FnOnce(&mut Enter) -> R,
F: FnOnce() -> R,
{
EXECUTOR.with(|cell| {
match cell.get() {
State::Ready(_) | State::Active => {
panic!("default executor already set for execution context")
}
_ => {}
}
let was = cell.get();
// Ensure that the executor is removed from the thread-local context
// when leaving the scope. This handles cases that involve panicking.
struct Reset<'a>(&'a Cell<State>);
struct Reset<'a>(&'a Cell<State>, State);
impl<'a> Drop for Reset<'a> {
fn drop(&mut self) {
self.0.set(State::Empty);
self.0.set(self.1);
}
}
let _reset = Reset(cell);
let _reset = Reset(cell, was);
// While scary, this is safe. The function takes a
// `&mut Executor`, which guarantees that the reference lives for the
@@ -180,7 +174,7 @@ where
cell.set(State::Ready(executor));
f(enter)
f()
})
}
@@ -202,12 +196,10 @@ mod tests {
#[test]
fn nested_default_executor_status() {
let mut enter = super::super::enter().unwrap();
let _enter = super::super::enter().unwrap();
let mut executor = DefaultExecutor::current();
let result = with_default(&mut executor, &mut enter, |_| {
DefaultExecutor::current().status()
});
let result = with_default(&mut executor, || DefaultExecutor::current().status());
assert!(result.err().unwrap().is_shutdown())
}
+3 -4
View File
@@ -58,7 +58,6 @@ use std::task::Waker;
use std::time::{Duration, Instant};
use std::{fmt, usize};
use tokio_executor::park::{Park, Unpark};
use tokio_executor::Enter;
use tokio_sync::task::AtomicWaker;
/// The core reactor, or event loop.
@@ -162,9 +161,9 @@ fn _assert_kinds() {
/// # Panics
///
/// This function panics if there already is a default reactor set.
pub fn with_default<F, R>(handle: &Handle, enter: &mut Enter, f: F) -> R
pub fn with_default<F, R>(handle: &Handle, f: F) -> R
where
F: FnOnce(&mut Enter) -> R,
F: FnOnce() -> R,
{
// Ensure that the executor is removed from the thread-local context
// when leaving the scope. This handles cases that involve panicking.
@@ -203,7 +202,7 @@ where
*current = Some(handle.clone());
}
f(enter)
f()
})
}
+2 -3
View File
@@ -15,7 +15,6 @@ use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use tokio_executor::park::Park;
use tokio_executor::Enter;
/// Builds a thread pool with custom configuration values.
///
@@ -261,7 +260,7 @@ impl Builder {
/// use tokio_threadpool::Builder;
///
/// let thread_pool = Builder::new()
/// .around_worker(|worker, _| {
/// .around_worker(|worker| {
/// println!("worker is starting up");
/// worker.run();
/// println!("worker is shutting down");
@@ -272,7 +271,7 @@ impl Builder {
/// [`Worker::run`]: struct.Worker.html#method.run
pub fn around_worker<F>(&mut self, f: F) -> &mut Self
where
F: Fn(&Worker, &mut Enter) + Send + Sync + 'static,
F: Fn(&Worker) + Send + Sync + 'static,
{
self.config.around_worker = Some(Callback::new(f));
self
+4 -5
View File
@@ -1,23 +1,22 @@
use crate::worker::Worker;
use std::fmt;
use std::sync::Arc;
use tokio_executor::Enter;
#[derive(Clone)]
pub(crate) struct Callback {
f: Arc<dyn Fn(&Worker, &mut Enter) + Send + Sync>,
f: Arc<dyn Fn(&Worker) + Send + Sync>,
}
impl Callback {
pub fn new<F>(f: F) -> Self
where
F: Fn(&Worker, &mut Enter) + Send + Sync + 'static,
F: Fn(&Worker) + Send + Sync + 'static,
{
Callback { f: Arc::new(f) }
}
pub fn call(&self, worker: &Worker, enter: &mut Enter) {
(self.f)(worker, enter)
pub fn call(&self, worker: &Worker) {
(self.f)(worker)
}
}
+3 -3
View File
@@ -119,11 +119,11 @@ impl Worker {
let mut sender = Sender { pool };
// Enter an execution context
let mut enter = tokio_executor::enter().unwrap();
let _enter = tokio_executor::enter().unwrap();
tokio_executor::with_default(&mut sender, &mut enter, |enter| {
tokio_executor::with_default(&mut sender, || {
if let Some(ref callback) = self.pool.config.around_worker {
callback.call(self, enter);
callback.call(self);
} else {
self.run();
}
+3 -3
View File
@@ -33,7 +33,7 @@ fn natural_shutdown_simple_futures() {
let num_dec = num_dec.clone();
Builder::new()
.around_worker(move |w, _| {
.around_worker(move |w| {
num_inc.fetch_add(1, Relaxed);
w.run();
num_dec.fetch_add(1, Relaxed);
@@ -115,7 +115,7 @@ fn force_shutdown_drops_futures() {
let b = num_dec.clone();
let pool = Builder::new()
.around_worker(move |w, _| {
.around_worker(move |w| {
a.fetch_add(1, Relaxed);
w.run();
b.fetch_add(1, Relaxed);
@@ -173,7 +173,7 @@ fn drop_threadpool_drops_futures() {
let pool = Builder::new()
.max_blocking(2)
.pool_size(20)
.around_worker(move |w, _| {
.around_worker(move |w| {
a.fetch_add(1, Relaxed);
w.run();
b.fetch_add(1, Relaxed);
+3 -9
View File
@@ -185,7 +185,7 @@ impl Runtime {
fn enter<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut current_thread::Entered<'_, Parker>) -> R,
F: FnOnce(&mut current_thread::CurrentThread<Parker>) -> R,
{
let Runtime {
ref reactor_handle,
@@ -195,12 +195,9 @@ impl Runtime {
..
} = *self;
// Binds an executor to this thread
let mut enter = tokio_executor::enter().expect("Multiple executors at once");
// This will set the default handle and timer to use inside the closure
// and run the future.
tokio_reactor::with_default(&reactor_handle, &mut enter, |enter| {
tokio_reactor::with_default(&reactor_handle, || {
clock::with_default(clock, || {
timer::with_default(&timer_handle, || {
// The TaskExecutor is a fake executor that looks into the
@@ -209,10 +206,7 @@ impl Runtime {
// to run the provided future, another to install as the default
// one). We use the fake one here as the default one.
let mut default_executor = current_thread::TaskExecutor::current();
tokio_executor::with_default(&mut default_executor, enter, |enter| {
let mut executor = executor.enter(enter);
f(&mut executor)
})
tokio_executor::with_default(&mut default_executor, || f(executor))
})
})
})
+2 -2
View File
@@ -336,10 +336,10 @@ impl Builder {
let pool = self
.threadpool_builder
.around_worker(move |w, enter| {
.around_worker(move |w| {
let index = w.id().to_usize();
tokio_reactor::with_default(&reactor_handles[index], enter, |_| {
tokio_reactor::with_default(&reactor_handles[index], || {
clock::with_default(&clock, || {
timer::with_default(&timer_handles[index], || {
trace::dispatcher::with_default(&dispatch, || {