When a task scope produces <= 1 task to run, run it on the calling thread immediately. (#932)

While generally speaking the calling thread would have picked up the task first anyways, I don't think it makes much sense usually to block the calling thread until another thread wakes and does the work.
This commit is contained in:
Philip Degarmo 2020-11-27 12:14:44 -08:00 committed by GitHub
parent 7d4cb70d92
commit ec8fd57c45
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -167,7 +167,6 @@ impl TaskPool {
let executor: &async_executor::Executor = &*self.executor; let executor: &async_executor::Executor = &*self.executor;
let executor: &'scope async_executor::Executor = unsafe { mem::transmute(executor) }; let executor: &'scope async_executor::Executor = unsafe { mem::transmute(executor) };
let fut = async move {
let mut scope = Scope { let mut scope = Scope {
executor, executor,
spawned: Vec::new(), spawned: Vec::new(),
@ -175,6 +174,12 @@ impl TaskPool {
f(&mut scope); f(&mut scope);
if scope.spawned.is_empty() {
Vec::default()
} else if scope.spawned.len() == 1 {
vec![future::block_on(&mut scope.spawned[0])]
} else {
let fut = async move {
let mut results = Vec::with_capacity(scope.spawned.len()); let mut results = Vec::with_capacity(scope.spawned.len());
for task in scope.spawned { for task in scope.spawned {
results.push(task.await); results.push(task.await);
@ -207,6 +212,7 @@ impl TaskPool {
self.executor.try_tick(); self.executor.try_tick();
} }
} }
}
/// Spawns a static future onto the thread pool. The returned Task is a future. It can also be /// Spawns a static future onto the thread pool. The returned Task is a future. It can also be
/// cancelled and "detached" allowing it to continue running without having to be polled by the /// cancelled and "detached" allowing it to continue running without having to be polled by the