Skip to content

Commit 726ad2c

Browse files
committed
Spawn several threads when we fail to enqueue work in the blocking threadpool
1 parent 568f6a6 commit 726ad2c

File tree

1 file changed

+25
-21
lines changed

1 file changed

+25
-21
lines changed

src/task/blocking.rs

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -59,27 +59,31 @@ fn maybe_create_another_blocking_thread() {
5959
return;
6060
}
6161

62-
// We want to avoid having all threads terminate at
63-
// exactly the same time, causing thundering herd
64-
// effects. We want to stagger their destruction over
65-
// 10 seconds or so to make the costs fade into
66-
// background noise.
67-
//
68-
// Generate a simple random number of milliseconds
69-
let rand_sleep_ms = u64::from(random(10_000));
70-
71-
thread::Builder::new()
72-
.name("async-blocking-driver-dynamic".to_string())
73-
.spawn(move || {
74-
let wait_limit = Duration::from_millis(1000 + rand_sleep_ms);
75-
76-
DYNAMIC_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
77-
while let Ok(task) = POOL.receiver.recv_timeout(wait_limit) {
78-
abort_on_panic(|| task.run());
79-
}
80-
DYNAMIC_THREAD_COUNT.fetch_sub(1, Ordering::Relaxed);
81-
})
82-
.expect("cannot start a dynamic thread driving blocking tasks");
62+
let n_to_spawn = std::cmp::min(2 + (workers / 10), 10);
63+
64+
for _ in 0..n_to_spawn {
65+
// We want to avoid having all threads terminate at
66+
// exactly the same time, causing thundering herd
67+
// effects. We want to stagger their destruction over
68+
// 10 seconds or so to make the costs fade into
69+
// background noise.
70+
//
71+
// Generate a simple random number of milliseconds
72+
let rand_sleep_ms = u64::from(random(10_000));
73+
74+
thread::Builder::new()
75+
.name("async-blocking-driver-dynamic".to_string())
76+
.spawn(move || {
77+
let wait_limit = Duration::from_millis(1000 + rand_sleep_ms);
78+
79+
DYNAMIC_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
80+
while let Ok(task) = POOL.receiver.recv_timeout(wait_limit) {
81+
abort_on_panic(|| task.run());
82+
}
83+
DYNAMIC_THREAD_COUNT.fetch_sub(1, Ordering::Relaxed);
84+
})
85+
.expect("cannot start a dynamic thread driving blocking tasks");
86+
}
8387
}
8488

8589
// Enqueues work, attempting to send to the threadpool in a

0 commit comments

Comments
 (0)