Debian Codegraph @

third_party/rust/tokio/src/runtime/blocking/pool.rs

raw
1 //! Thread pool for blocking operations
2
3 use crate::loom::sync::{Arc, Condvar, Mutex};
4 use crate::loom::thread;
5 use crate::runtime::blocking::schedule::BlockingSchedule;
6 use crate::runtime::blocking::{shutdown, BlockingTask};
7 use crate::runtime::builder::ThreadNameFn;
8 use crate::runtime::task::{self, JoinHandle};
9 use crate::runtime::{Builder, Callback, Handle, BOX_FUTURE_THRESHOLD};
10 use crate::util::metric_atomics::MetricAtomicUsize;
11
12 use std::collections::{HashMap, VecDeque};
13 use std::fmt;
14 use std::io;
15 use std::sync::atomic::Ordering;
16 use std::time::Duration;
17
18 pub(crate) struct BlockingPool {
19 spawner: Spawner,
20 shutdown_rx: shutdown::Receiver,
21 }
22
23 #[derive(Clone)]
24 pub(crate) struct Spawner {
25 inner: Arc<Inner>,
26 }
27
28 #[derive(Default)]
29 pub(crate) struct SpawnerMetrics {
30 num_threads: MetricAtomicUsize,
31 num_idle_threads: MetricAtomicUsize,
32 queue_depth: MetricAtomicUsize,
33 }
34
35 impl SpawnerMetrics {
36 fn num_threads(&self) -> usize {
37 self.num_threads.load(Ordering::Relaxed)
38 }
39
40 fn num_idle_threads(&self) -> usize {
41 self.num_idle_threads.load(Ordering::Relaxed)
42 }
43
44 cfg_unstable_metrics! {
45 fn queue_depth(&self) -> usize {
46 self.queue_depth.load(Ordering::Relaxed)
47 }
48 }
49
50 fn inc_num_threads(&self) {
51 self.num_threads.increment();
52 }
53
54 fn dec_num_threads(&self) {
55 self.num_threads.decrement();
56 }
57
58 fn inc_num_idle_threads(&self) {
59 self.num_idle_threads.increment();
60 }
61
62 fn dec_num_idle_threads(&self) -> usize {
63 self.num_idle_threads.decrement()
64 }
65
66 fn inc_queue_depth(&self) {
67 self.queue_depth.increment();
68 }
69
70 fn dec_queue_depth(&self) {
71 self.queue_depth.decrement();
72 }
73 }
74
75 struct Inner {
76 /// State shared between worker threads.
77 shared: Mutex<Shared>,
78
79 /// Pool threads wait on this.
80 condvar: Condvar,
81
82 /// Spawned threads use this name.
83 thread_name: ThreadNameFn,
84
85 /// Spawned thread stack size.
86 stack_size: Option<usize>,
87
88 /// Call after a thread starts.
89 after_start: Option<Callback>,
90
91 /// Call before a thread stops.
92 before_stop: Option<Callback>,
93
94 // Maximum number of threads.
95 thread_cap: usize,
96
97 // Customizable wait timeout.
98 keep_alive: Duration,
99
100 // Metrics about the pool.
101 metrics: SpawnerMetrics,
102 }
103
104 struct Shared {
105 queue: VecDeque<Task>,
106 num_notify: u32,
107 shutdown: bool,
108 shutdown_tx: Option<shutdown::Sender>,
109 /// Prior to shutdown, we clean up `JoinHandles` by having each timed-out
110 /// thread join on the previous timed-out thread. This is not strictly
111 /// necessary but helps avoid Valgrind false positives, see
112 /// <https://github.com/tokio-rs/tokio/commit/646fbae76535e397ef79dbcaacb945d4c829f666>
113 /// for more information.
114 last_exiting_thread: Option<thread::JoinHandle<()>>,
115 /// This holds the `JoinHandles` for all running threads; on shutdown, the thread
116 /// calling shutdown handles joining on these.
117 worker_threads: HashMap<usize, thread::JoinHandle<()>>,
118 /// This is a counter used to iterate `worker_threads` in a consistent order (for loom's
119 /// benefit).
120 worker_thread_index: usize,
121 }
122
123 pub(crate) struct Task {
124 task: task::UnownedTask<BlockingSchedule>,
125 mandatory: Mandatory,
126 }
127
128 #[derive(PartialEq, Eq)]
129 pub(crate) enum Mandatory {
130 #[cfg_attr(not(fs), allow(dead_code))]
131 Mandatory,
132 NonMandatory,
133 }
134
135 pub(crate) enum SpawnError {
136 /// Pool is shutting down and the task was not scheduled
137 ShuttingDown,
138 /// There are no worker threads available to take the task
139 /// and the OS failed to spawn a new one
140 NoThreads(io::Error),
141 }
142
143 impl From<SpawnError> for io::Error {
144 fn from(e: SpawnError) -> Self {
145 match e {
146 SpawnError::ShuttingDown => {
147 io::Error::new(io::ErrorKind::Other, "blocking pool shutting down")
148 }
149 SpawnError::NoThreads(e) => e,
150 }
151 }
152 }
153
154 impl Task {
155 pub(crate) fn new(task: task::UnownedTask<BlockingSchedule>, mandatory: Mandatory) -> Task {
156 Task { task, mandatory }
157 }
158
159 fn run(self) {
160 self.task.run();
161 }
162
163 fn shutdown_or_run_if_mandatory(self) {
164 match self.mandatory {
165 Mandatory::NonMandatory => self.task.shutdown(),
166 Mandatory::Mandatory => self.task.run(),
167 }
168 }
169 }
170
171 const KEEP_ALIVE: Duration = Duration::from_secs(10);
172
173 /// Runs the provided function on an executor dedicated to blocking operations.
174 /// Tasks will be scheduled as non-mandatory, meaning they may not get executed
175 /// in case of runtime shutdown.
176 #[track_caller]
177 #[cfg_attr(target_os = "wasi", allow(dead_code))]
178 pub(crate) fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
179 where
180 F: FnOnce() -> R + Send + 'static,
181 R: Send + 'static,
182 {
183 let rt = Handle::current();
184 rt.spawn_blocking(func)
185 }
186
187 cfg_fs! {
188 #[cfg_attr(any(
189 all(loom, not(test)), // the function is covered by loom tests
190 test
191 ), allow(dead_code))]
192 /// Runs the provided function on an executor dedicated to blocking
193 /// operations. Tasks will be scheduled as mandatory, meaning they are
194 /// guaranteed to run unless a shutdown is already taking place. In case a
195 /// shutdown is already taking place, `None` will be returned.
196 pub(crate) fn spawn_mandatory_blocking<F, R>(func: F) -> Option<JoinHandle<R>>
197 where
198 F: FnOnce() -> R + Send + 'static,
199 R: Send + 'static,
200 {
201 let rt = Handle::current();
202 rt.inner.blocking_spawner().spawn_mandatory_blocking(&rt, func)
203 }
204 }
205
206 // ===== impl BlockingPool =====
207
208 impl BlockingPool {
209 pub(crate) fn new(builder: &Builder, thread_cap: usize) -> BlockingPool {
210 let (shutdown_tx, shutdown_rx) = shutdown::channel();
211 let keep_alive = builder.keep_alive.unwrap_or(KEEP_ALIVE);
212
213 BlockingPool {
214 spawner: Spawner {
215 inner: Arc::new(Inner {
216 shared: Mutex::new(Shared {
217 queue: VecDeque::new(),
218 num_notify: 0,
219 shutdown: false,
220 shutdown_tx: Some(shutdown_tx),
221 last_exiting_thread: None,
222 worker_threads: HashMap::new(),
223 worker_thread_index: 0,
224 }),
225 condvar: Condvar::new(),
226 thread_name: builder.thread_name.clone(),
227 stack_size: builder.thread_stack_size,
228 after_start: builder.after_start.clone(),
229 before_stop: builder.before_stop.clone(),
230 thread_cap,
231 keep_alive,
232 metrics: SpawnerMetrics::default(),
233 }),
234 },
235 shutdown_rx,
236 }
237 }
238
239 pub(crate) fn spawner(&self) -> &Spawner {
240 &self.spawner
241 }
242
243 pub(crate) fn shutdown(&mut self, timeout: Option<Duration>) {
244 let mut shared = self.spawner.inner.shared.lock();
245
246 // The function can be called multiple times. First, by explicitly
247 // calling `shutdown` then by the drop handler calling `shutdown`. This
248 // prevents shutting down twice.
249 if shared.shutdown {
250 return;
251 }
252
253 shared.shutdown = true;
254 shared.shutdown_tx = None;
255 self.spawner.inner.condvar.notify_all();
256
257 let last_exited_thread = std::mem::take(&mut shared.last_exiting_thread);
258 let workers = std::mem::take(&mut shared.worker_threads);
259
260 drop(shared);
261
262 if self.shutdown_rx.wait(timeout) {
263 let _ = last_exited_thread.map(thread::JoinHandle::join);
264
265 // Loom requires that execution be deterministic, so sort by thread ID before joining.
266 // (HashMaps use a randomly-seeded hash function, so the order is nondeterministic)
267 #[cfg(loom)]
268 let workers: Vec<(usize, thread::JoinHandle<()>)> = {
269 let mut workers: Vec<_> = workers.into_iter().collect();
270 workers.sort_by_key(|(id, _)| *id);
271 workers
272 };
273
274 for (_id, handle) in workers {
275 let _ = handle.join();
276 }
277 }
278 }
279 }
280
281 impl Drop for BlockingPool {
282 fn drop(&mut self) {
283 self.shutdown(None);
284 }
285 }
286
287 impl fmt::Debug for BlockingPool {
288 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
289 fmt.debug_struct("BlockingPool").finish()
290 }
291 }
292
293 // ===== impl Spawner =====
294
295 impl Spawner {
296 #[track_caller]
297 pub(crate) fn spawn_blocking<F, R>(&self, rt: &Handle, func: F) -> JoinHandle<R>
298 where
299 F: FnOnce() -> R + Send + 'static,
300 R: Send + 'static,
301 {
302 let (join_handle, spawn_result) =
303 if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
304 self.spawn_blocking_inner(Box::new(func), Mandatory::NonMandatory, None, rt)
305 } else {
306 self.spawn_blocking_inner(func, Mandatory::NonMandatory, None, rt)
307 };
308
309 match spawn_result {
310 Ok(()) => join_handle,
311 // Compat: do not panic here, return the join_handle even though it will never resolve
312 Err(SpawnError::ShuttingDown) => join_handle,
313 Err(SpawnError::NoThreads(e)) => {
314 panic!("OS can't spawn worker thread: {}", e)
315 }
316 }
317 }
318
319 cfg_fs! {
320 #[track_caller]
321 #[cfg_attr(any(
322 all(loom, not(test)), // the function is covered by loom tests
323 test
324 ), allow(dead_code))]
325 pub(crate) fn spawn_mandatory_blocking<F, R>(&self, rt: &Handle, func: F) -> Option<JoinHandle<R>>
326 where
327 F: FnOnce() -> R + Send + 'static,
328 R: Send + 'static,
329 {
330 let (join_handle, spawn_result) = if cfg!(debug_assertions) && std::mem::size_of::<F>() > BOX_FUTURE_THRESHOLD {
331 self.spawn_blocking_inner(
332 Box::new(func),
333 Mandatory::Mandatory,
334 None,
335 rt,
336 )
337 } else {
338 self.spawn_blocking_inner(
339 func,
340 Mandatory::Mandatory,
341 None,
342 rt,
343 )
344 };
345
346 if spawn_result.is_ok() {
347 Some(join_handle)
348 } else {
349 None
350 }
351 }
352 }
353
354 #[track_caller]
355 pub(crate) fn spawn_blocking_inner<F, R>(
356 &self,
357 func: F,
358 is_mandatory: Mandatory,
359 name: Option<&str>,
360 rt: &Handle,
361 ) -> (JoinHandle<R>, Result<(), SpawnError>)
362 where
363 F: FnOnce() -> R + Send + 'static,
364 R: Send + 'static,
365 {
366 let fut = BlockingTask::new(func);
367 let id = task::Id::next();
368 #[cfg(all(tokio_unstable, feature = "tracing"))]
369 let fut = {
370 use tracing::Instrument;
371 let location = std::panic::Location::caller();
372 let span = tracing::trace_span!(
373 target: "tokio::task::blocking",
374 "runtime.spawn",
375 kind = %"blocking",
376 task.name = %name.unwrap_or_default(),
377 task.id = id.as_u64(),
378 "fn" = %std::any::type_name::<F>(),
379 loc.file = location.file(),
380 loc.line = location.line(),
381 loc.col = location.column(),
382 );
383 fut.instrument(span)
384 };
385
386 #[cfg(not(all(tokio_unstable, feature = "tracing")))]
387 let _ = name;
388
389 let (task, handle) = task::unowned(fut, BlockingSchedule::new(rt), id);
390
391 let spawned = self.spawn_task(Task::new(task, is_mandatory), rt);
392 (handle, spawned)
393 }
394
395 fn spawn_task(&self, task: Task, rt: &Handle) -> Result<(), SpawnError> {
396 let mut shared = self.inner.shared.lock();
397
398 if shared.shutdown {
399 // Shutdown the task: it's fine to shutdown this task (even if
400 // mandatory) because it was scheduled after the shutdown of the
401 // runtime began.
402 task.task.shutdown();
403
404 // no need to even push this task; it would never get picked up
405 return Err(SpawnError::ShuttingDown);
406 }
407
408 shared.queue.push_back(task);
409 self.inner.metrics.inc_queue_depth();
410
411 if self.inner.metrics.num_idle_threads() == 0 {
412 // No threads are able to process the task.
413
414 if self.inner.metrics.num_threads() == self.inner.thread_cap {
415 // At max number of threads
416 } else {
417 assert!(shared.shutdown_tx.is_some());
418 let shutdown_tx = shared.shutdown_tx.clone();
419
420 if let Some(shutdown_tx) = shutdown_tx {
421 let id = shared.worker_thread_index;
422
423 match self.spawn_thread(shutdown_tx, rt, id) {
424 Ok(handle) => {
425 self.inner.metrics.inc_num_threads();
426 shared.worker_thread_index += 1;
427 shared.worker_threads.insert(id, handle);
428 }
429 Err(ref e)
430 if is_temporary_os_thread_error(e)
431 && self.inner.metrics.num_threads() > 0 =>
432 {
433 // OS temporarily failed to spawn a new thread.
434 // The task will be picked up eventually by a currently
435 // busy thread.
436 }
437 Err(e) => {
438 // The OS refused to spawn the thread and there is no thread
439 // to pick up the task that has just been pushed to the queue.
440 return Err(SpawnError::NoThreads(e));
441 }
442 }
443 }
444 }
445 } else {
446 // Notify an idle worker thread. The notification counter
447 // is used to count the needed amount of notifications
448 // exactly. Thread libraries may generate spurious
449 // wakeups, this counter is used to keep us in a
450 // consistent state.
451 self.inner.metrics.dec_num_idle_threads();
452 shared.num_notify += 1;
453 self.inner.condvar.notify_one();
454 }
455
456 Ok(())
457 }
458
459 fn spawn_thread(
460 &self,
461 shutdown_tx: shutdown::Sender,
462 rt: &Handle,
463 id: usize,
464 ) -> std::io::Result<thread::JoinHandle<()>> {
465 let mut builder = thread::Builder::new().name((self.inner.thread_name)());
466
467 if let Some(stack_size) = self.inner.stack_size {
468 builder = builder.stack_size(stack_size);
469 }
470
471 let rt = rt.clone();
472
473 builder.spawn(move || {
474 // Only the reference should be moved into the closure
475 let _enter = rt.enter();
476 rt.inner.blocking_spawner().inner.run(id);
477 drop(shutdown_tx);
478 })
479 }
480 }
481
482 cfg_unstable_metrics! {
483 impl Spawner {
484 pub(crate) fn num_threads(&self) -> usize {
485 self.inner.metrics.num_threads()
486 }
487
488 pub(crate) fn num_idle_threads(&self) -> usize {
489 self.inner.metrics.num_idle_threads()
490 }
491
492 pub(crate) fn queue_depth(&self) -> usize {
493 self.inner.metrics.queue_depth()
494 }
495 }
496 }
497
498 // Tells whether the error when spawning a thread is temporary.
499 #[inline]
500 fn is_temporary_os_thread_error(error: &std::io::Error) -> bool {
501 matches!(error.kind(), std::io::ErrorKind::WouldBlock)
502 }
503
504 impl Inner {
505 fn run(&self, worker_thread_id: usize) {
506 if let Some(f) = &self.after_start {
507 f();
508 }
509
510 let mut shared = self.shared.lock();
511 let mut join_on_thread = None;
512
513 'main: loop {
514 // BUSY
515 while let Some(task) = shared.queue.pop_front() {
516 self.metrics.dec_queue_depth();
517 drop(shared);
518 task.run();
519
520 shared = self.shared.lock();
521 }
522
523 // IDLE
524 self.metrics.inc_num_idle_threads();
525
526 while !shared.shutdown {
527 let lock_result = self.condvar.wait_timeout(shared, self.keep_alive).unwrap();
528
529 shared = lock_result.0;
530 let timeout_result = lock_result.1;
531
532 if shared.num_notify != 0 {
533 // We have received a legitimate wakeup,
534 // acknowledge it by decrementing the counter
535 // and transition to the BUSY state.
536 shared.num_notify -= 1;
537 break;
538 }
539
540 // Even if the condvar "timed out", if the pool is entering the
541 // shutdown phase, we want to perform the cleanup logic.
542 if !shared.shutdown && timeout_result.timed_out() {
543 // We'll join the prior timed-out thread's JoinHandle after dropping the lock.
544 // This isn't done when shutting down, because the thread calling shutdown will
545 // handle joining everything.
546 let my_handle = shared.worker_threads.remove(&worker_thread_id);
547 join_on_thread = std::mem::replace(&mut shared.last_exiting_thread, my_handle);
548
549 break 'main;
550 }
551
552 // Spurious wakeup detected, go back to sleep.
553 }
554
555 if shared.shutdown {
556 // Drain the queue
557 while let Some(task) = shared.queue.pop_front() {
558 self.metrics.dec_queue_depth();
559 drop(shared);
560
561 task.shutdown_or_run_if_mandatory();
562
563 shared = self.shared.lock();
564 }
565
566 // Work was produced, and we "took" it (by decrementing num_notify).
567 // This means that num_idle was decremented once for our wakeup.
568 // But, since we are exiting, we need to "undo" that, as we'll stay idle.
569 self.metrics.inc_num_idle_threads();
570 // NOTE: Technically we should also do num_notify++ and notify again,
571 // but since we're shutting down anyway, that won't be necessary.
572 break;
573 }
574 }
575
576 // Thread exit
577 self.metrics.dec_num_threads();
578
579 // num_idle should now be tracked exactly, panic
580 // with a descriptive message if it is not the
581 // case.
582 let prev_idle = self.metrics.dec_num_idle_threads();
583 assert!(
584 prev_idle >= self.metrics.num_idle_threads(),
585 "num_idle_threads underflowed on thread exit"
586 );
587
588 if shared.shutdown && self.metrics.num_threads() == 0 {
589 self.condvar.notify_one();
590 }
591
592 drop(shared);
593
594 if let Some(f) = &self.before_stop {
595 f();
596 }
597
598 if let Some(handle) = join_on_thread {
599 let _ = handle.join();
600 }
601 }
602 }
603
604 impl fmt::Debug for Spawner {
605 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
606 fmt.debug_struct("blocking::Spawner").finish()
607 }
608 }