Skip to content

Improve thread startup/shutdown algorithm in spawn_blocking #510

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

Merged
merged 3 commits into from Nov 11, 2019
Merged
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
27 changes: 19 additions & 8 deletions src/task/spawn_blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crossbeam_channel::{unbounded, Receiver, Sender};
use once_cell::sync::Lazy;

use crate::task::{JoinHandle, Task};
use crate::utils::{abort_on_panic, random};
use crate::utils::abort_on_panic;

/// Spawns a blocking task.
///
Expand Down Expand Up @@ -68,16 +68,13 @@ static POOL: Lazy<Pool> = Lazy::new(|| {

fn start_thread() {
SLEEPING.fetch_add(1, Ordering::SeqCst);

// Generate a random duration of time between 1 second and 10 seconds. If the thread doesn't
// receive the next task in this duration of time, it will stop running.
let timeout = Duration::from_millis(1000 + u64::from(random(9_000)));
let timeout = Duration::from_secs(1);

thread::Builder::new()
.name("async-std/blocking".to_string())
.spawn(move || {
loop {
let task = match POOL.receiver.recv_timeout(timeout) {
let mut task = match POOL.receiver.recv_timeout(timeout) {
Ok(task) => task,
Err(_) => {
// Check whether this is the last sleeping thread.
Expand All @@ -100,8 +97,22 @@ fn start_thread() {
start_thread();
}

// Run the task.
abort_on_panic(|| task.run());
loop {
// Run the task.
abort_on_panic(|| task.run());

// Try taking another task if there are any available.
task = match POOL.receiver.try_recv() {
Ok(task) => task,
Err(_) => break,
};
}

// If there is at least one sleeping thread, stop this thread instead of putting it
// to sleep.
if SLEEPING.load(Ordering::SeqCst) > 0 {
return;
}

SLEEPING.fetch_add(1, Ordering::SeqCst);
}
Expand Down