| 1 | //! Implementation of the thread pool itself. |
| 2 | |
| 3 | use std::{ |
| 4 | fmt, |
| 5 | future::Future, |
| 6 | ops::{Range, RangeInclusive, RangeTo, RangeToInclusive}, |
| 7 | sync::{ |
| 8 | atomic::{AtomicUsize, Ordering}, |
| 9 | Arc, |
| 10 | Condvar, |
| 11 | Mutex, |
| 12 | }, |
| 13 | thread, |
| 14 | time::{Duration, Instant}, |
| 15 | }; |
| 16 | |
| 17 | use crossbeam_channel::{bounded, unbounded, Receiver, Sender}; |
| 18 | use once_cell::sync::Lazy; |
| 19 | |
| 20 | use crate::{ |
| 21 | error::PoolFullError, |
| 22 | task::{Coroutine, Task}, |
| 23 | worker::{Listener, Worker}, |
| 24 | }; |
| 25 | |
| 26 | #[cfg(threadfin_has_atomic64)] |
| 27 | type AtomicCounter = std::sync::atomic::AtomicU64; |
| 28 | |
| 29 | #[cfg(not(threadfin_has_atomic64))] |
| 30 | type AtomicCounter = std::sync::atomic::AtomicU32; |
| 31 | |
| 32 | /// A value describing a size constraint for a thread pool. |
| 33 | /// |
| 34 | /// Any size constraint can be wrapped in [`PerCore`] to be made relative to the |
| 35 | /// number of available CPU cores on the current system. |
| 36 | /// |
| 37 | /// See [`Builder::size`] for details. |
| 38 | pub trait SizeConstraint { |
| 39 | /// Get the minimum number of threads to be in the thread pool. |
| 40 | fn min(&self) -> usize; |
| 41 | |
| 42 | /// Get the maximum number of threads to be in the thread pool. |
| 43 | fn max(&self) -> usize; |
| 44 | } |
| 45 | |
| 46 | impl SizeConstraint for usize { |
| 47 | fn min(&self) -> usize { |
| 48 | *self |
| 49 | } |
| 50 | |
| 51 | fn max(&self) -> usize { |
| 52 | *self |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl SizeConstraint for Range<usize> { |
| 57 | fn min(&self) -> usize { |
| 58 | self.start |
| 59 | } |
| 60 | |
| 61 | fn max(&self) -> usize { |
| 62 | self.end |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl SizeConstraint for RangeInclusive<usize> { |
| 67 | fn min(&self) -> usize { |
| 68 | *self.start() |
| 69 | } |
| 70 | |
| 71 | fn max(&self) -> usize { |
| 72 | *self.end() |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | impl SizeConstraint for RangeTo<usize> { |
| 77 | fn min(&self) -> usize { |
| 78 | 0 |
| 79 | } |
| 80 | |
| 81 | fn max(&self) -> usize { |
| 82 | self.end |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl SizeConstraint for RangeToInclusive<usize> { |
| 87 | fn min(&self) -> usize { |
| 88 | 0 |
| 89 | } |
| 90 | |
| 91 | fn max(&self) -> usize { |
| 92 | self.end |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// Modifies a size constraint to be per available CPU core. |
| 97 | /// |
| 98 | /// # Examples |
| 99 | /// |
| 100 | /// ``` |
| 101 | /// # use threadfin::PerCore; |
| 102 | /// // one thread per core |
| 103 | /// let size = PerCore(1); |
| 104 | /// |
| 105 | /// // four threads per core |
| 106 | /// let size = PerCore(4); |
| 107 | /// |
| 108 | /// // at least 1 thread per core and at most 2 threads per core |
| 109 | /// let size = PerCore(1..2); |
| 110 | /// ``` |
| 111 | pub struct PerCore<T>(pub T); |
| 112 | |
| 113 | static CORE_COUNT: Lazy<usize> = Lazy::new(|| num_cpus::get().max(1)); |
| 114 | |
| 115 | impl<T> From<T> for PerCore<T> { |
| 116 | fn from(size: T) -> Self { |
| 117 | Self(size) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | impl<T: SizeConstraint> SizeConstraint for PerCore<T> { |
| 122 | fn min(&self) -> usize { |
| 123 | *CORE_COUNT * self.0.min() |
| 124 | } |
| 125 | |
| 126 | fn max(&self) -> usize { |
| 127 | *CORE_COUNT * self.0.max() |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /// A builder for constructing a customized [`ThreadPool`]. |
| 132 | /// |
| 133 | /// # Examples |
| 134 | /// |
| 135 | /// ``` |
| 136 | /// let custom_pool = threadfin::builder() |
| 137 | /// .name("my-pool") |
| 138 | /// .size(2) |
| 139 | /// .build(); |
| 140 | /// ``` |
| 141 | #[derive(Debug)] |
| 142 | pub struct Builder { |
| 143 | name: Option<String>, |
| 144 | size: Option<(usize, usize)>, |
| 145 | stack_size: Option<usize>, |
| 146 | queue_limit: Option<usize>, |
| 147 | worker_concurrency_limit: usize, |
| 148 | keep_alive: Duration, |
| 149 | } |
| 150 | |
| 151 | impl Default for Builder { |
| 152 | fn default() -> Self { |
| 153 | Self { |
| 154 | name: None, |
| 155 | size: None, |
| 156 | stack_size: None, |
| 157 | queue_limit: None, |
| 158 | worker_concurrency_limit: 16, |
| 159 | keep_alive: Duration::from_secs(60), |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | impl Builder { |
| 165 | /// Set a custom thread name for threads spawned by this thread pool. |
| 166 | /// |
| 167 | /// # Panics |
| 168 | /// |
| 169 | /// Panics if the name contains null bytes (`\0`). |
| 170 | /// |
| 171 | /// # Examples |
| 172 | /// |
| 173 | /// ``` |
| 174 | /// let pool = threadfin::builder().name("my-pool").build(); |
| 175 | /// ``` |
| 176 | pub fn name<T: Into<String>>(mut self, name: T) -> Self { |
| 177 | let name = name.into(); |
| 178 | |
| 179 | if name.as_bytes().contains(&0) { |
| 180 | panic!("thread pool name must not contain null bytes"); |
| 181 | } |
| 182 | |
| 183 | self.name = Some(name); |
| 184 | self |
| 185 | } |
| 186 | |
| 187 | /// Set the number of threads to be managed by this thread pool. |
| 188 | /// |
| 189 | /// If a `usize` is supplied, the pool will have a fixed number of threads. |
| 190 | /// If a range is supplied, the lower bound will be the core pool size while |
| 191 | /// the upper bound will be a maximum pool size the pool is allowed to burst |
| 192 | /// up to when the core threads are busy. |
| 193 | /// |
| 194 | /// Any size constraint can be wrapped in [`PerCore`] to be made relative to |
| 195 | /// the number of available CPU cores on the current system. |
| 196 | /// |
| 197 | /// If not set, a reasonable size will be selected based on the number of |
| 198 | /// CPU cores on the current system. |
| 199 | /// |
| 200 | /// # Examples |
| 201 | /// |
| 202 | /// ``` |
| 203 | /// // Create a thread pool with exactly 2 threads. |
| 204 | /// let pool = threadfin::builder().size(2).build(); |
| 205 | /// ``` |
| 206 | /// |
| 207 | /// ``` |
| 208 | /// // Create a thread pool with no idle threads, but will spawn up to 4 |
| 209 | /// // threads lazily when there's work to be done. |
| 210 | /// let pool = threadfin::builder().size(0..4).build(); |
| 211 | /// |
| 212 | /// // Or equivalently: |
| 213 | /// let pool = threadfin::builder().size(..4).build(); |
| 214 | /// ``` |
| 215 | /// |
| 216 | /// ``` |
| 217 | /// use threadfin::PerCore; |
| 218 | /// |
| 219 | /// // Create a thread pool with two threads per core. |
| 220 | /// let pool = threadfin::builder().size(PerCore(2)).build(); |
| 221 | /// ``` |
| 222 | /// |
| 223 | /// # Panics |
| 224 | /// |
| 225 | /// Panics if an invalid range is supplied with a lower bound larger than |
| 226 | /// the upper bound, or if the upper bound is 0. |
| 227 | pub fn size<S: SizeConstraint>(mut self, size: S) -> Self { |
| 228 | let (min, max) = (size.min(), size.max()); |
| 229 | |
| 230 | if min > max { |
| 231 | panic!("thread pool minimum size cannot be larger than maximum size"); |
| 232 | } |
| 233 | |
| 234 | if max == 0 { |
| 235 | panic!("thread pool maximum size must be non-zero"); |
| 236 | } |
| 237 | |
| 238 | self.size = Some((min, max)); |
| 239 | self |
| 240 | } |
| 241 | |
| 242 | /// Set the size of the stack (in bytes) for threads in this thread pool. |
| 243 | /// |
| 244 | /// The actual stack size may be greater than this value if the platform |
| 245 | /// enforces a larger minimum stack size. |
| 246 | /// |
| 247 | /// The stack size if not specified will be the default size for new Rust |
| 248 | /// threads, currently 2 MiB. This can also be overridden by setting the |
| 249 | /// `RUST_MIN_STACK` environment variable if not specified in code. |
| 250 | /// |
| 251 | /// # Examples |
| 252 | /// |
| 253 | /// ``` |
| 254 | /// // Worker threads will have a stack size of at least 32 KiB. |
| 255 | /// let pool = threadfin::builder().stack_size(32 * 1024).build(); |
| 256 | /// ``` |
| 257 | pub fn stack_size(mut self, size: usize) -> Self { |
| 258 | self.stack_size = Some(size); |
| 259 | self |
| 260 | } |
| 261 | |
| 262 | /// Set a maximum number of pending tasks allowed to be submitted before |
| 263 | /// blocking. |
| 264 | /// |
| 265 | /// If set to zero, queueing will be disabled and attempting to execute a |
| 266 | /// new task will block until an idle worker thread can immediately begin |
| 267 | /// executing the task or a new worker thread can be created to execute the |
| 268 | /// task. |
| 269 | /// |
| 270 | /// If not set, no limit is enforced. |
| 271 | pub fn queue_limit(mut self, limit: usize) -> Self { |
| 272 | self.queue_limit = Some(limit); |
| 273 | self |
| 274 | } |
| 275 | |
| 276 | /// Set a duration for how long to keep idle worker threads alive. |
| 277 | /// |
| 278 | /// If the pool has more than the minimum configured number of threads and |
| 279 | /// threads remain idle for more than this duration, they will be terminated |
| 280 | /// until the minimum thread count is reached. |
| 281 | pub fn keep_alive(mut self, duration: Duration) -> Self { |
| 282 | self.keep_alive = duration; |
| 283 | self |
| 284 | } |
| 285 | |
| 286 | /// Set a limit on the number of concurrent tasks that can be run by a |
| 287 | /// single worker thread. |
| 288 | /// |
| 289 | /// When executing asynchronous tasks, if the underlying future being |
| 290 | /// executed yields, that worker thread can begin working on new tasks |
| 291 | /// concurrently while waiting on the prior task to resume. This allows for |
| 292 | /// a primitive M:N scheduling model that supports running significantly |
| 293 | /// more futures concurrently than the number of threads in the thread pool. |
| 294 | /// |
| 295 | /// To prevent a worker thread from over-committing to too many tasks at |
| 296 | /// once (which could result in extra latency if a task wakes but its |
| 297 | /// assigned worker is too busy with other tasks) worker threads limit |
| 298 | /// themselves to a maximum number of concurrent tasks. This method allows |
| 299 | /// you to customize that limit. |
| 300 | /// |
| 301 | /// The default limit if not specified is 16. |
| 302 | pub fn worker_concurrency_limit(mut self, limit: usize) -> Self { |
| 303 | self.worker_concurrency_limit = limit; |
| 304 | self |
| 305 | } |
| 306 | |
| 307 | /// Create a thread pool according to the configuration set with this |
| 308 | /// builder. |
| 309 | pub fn build(self) -> ThreadPool { |
| 310 | let size = self.size.unwrap_or_else(|| { |
| 311 | let size = PerCore(1..2); |
| 312 | |
| 313 | (size.min(), size.max()) |
| 314 | }); |
| 315 | |
| 316 | let shared = Shared { |
| 317 | min_threads: size.0, |
| 318 | max_threads: size.1, |
| 319 | thread_count: Default::default(), |
| 320 | running_tasks_count: Default::default(), |
| 321 | completed_tasks_count: Default::default(), |
| 322 | panicked_tasks_count: Default::default(), |
| 323 | keep_alive: self.keep_alive, |
| 324 | shutdown_cvar: Condvar::new(), |
| 325 | }; |
| 326 | |
| 327 | let pool = ThreadPool { |
| 328 | thread_name: self.name, |
| 329 | stack_size: self.stack_size, |
| 330 | concurrency_limit: self.worker_concurrency_limit, |
| 331 | queue: self.queue_limit.map(bounded).unwrap_or_else(unbounded), |
| 332 | immediate_queue: bounded(0), |
| 333 | shared: Arc::new(shared), |
| 334 | }; |
| 335 | |
| 336 | for _ in 0..size.0 { |
| 337 | let result = pool.spawn_thread(None); |
| 338 | assert!(result.is_ok()); |
| 339 | } |
| 340 | |
| 341 | pool |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// A thread pool for running multiple tasks on a configurable group of threads. |
| 346 | /// |
| 347 | /// Thread pools can improve performance when executing a large number of |
| 348 | /// concurrent tasks since the expensive overhead of spawning threads is |
| 349 | /// minimized as threads are re-used for multiple tasks. Thread pools are also |
| 350 | /// useful for controlling and limiting parallelism. |
| 351 | /// |
| 352 | /// Dropping the thread pool will prevent any further tasks from being scheduled |
| 353 | /// on the pool and detaches all threads in the pool. If you want to block until |
| 354 | /// all pending tasks have completed and the pool is entirely shut down, then |
| 355 | /// use one of the available [`join`](ThreadPool::join) methods. |
| 356 | /// |
| 357 | /// # Pool size |
| 358 | /// |
| 359 | /// Every thread pool has a minimum and maximum number of worker threads that it |
| 360 | /// will spawn for executing tasks. This range is known as the _pool size_, and |
| 361 | /// affects pool behavior in the following ways: |
| 362 | /// |
| 363 | /// - **Minimum size**: A guaranteed number of threads that will always be |
| 364 | /// created and maintained by the thread pool. Threads will be eagerly created |
| 365 | /// to meet this minimum size when the pool is created, and at least this many |
| 366 | /// threads will be kept running in the pool until the pool is shut down. |
| 367 | /// - **Maximum size**: A limit on the number of additional threads to spawn to |
| 368 | /// execute more work. |
| 369 | /// |
| 370 | /// # Queueing |
| 371 | /// |
| 372 | /// If a new or existing worker thread is unable to immediately start processing |
| 373 | /// a submitted task, that task will be placed in a queue for worker threads to |
| 374 | /// take from when they complete their current tasks. Queueing is only used when |
| 375 | /// it is not possible to directly handoff a task to an existing thread and |
| 376 | /// spawning a new thread would exceed the pool's configured maximum size. |
| 377 | /// |
| 378 | /// By default, thread pools are configured to use an _unbounded_ queue which |
| 379 | /// can hold an unlimited number of pending tasks. This is a sensible default, |
| 380 | /// but is not desirable in all use-cases and can be changed with |
| 381 | /// [`Builder::queue_limit`]. |
| 382 | /// |
| 383 | /// # Monitoring |
| 384 | /// |
| 385 | /// Each pool instance provides methods for gathering various statistics on the |
| 386 | /// pool's usage, such as number of current number of threads, tasks completed |
| 387 | /// over time, and queued tasks. While these methods provide the most up-to-date |
| 388 | /// numbers upon invocation, they should not be used for controlling program |
| 389 | /// behavior since they can become immediately outdated due to the live nature |
| 390 | /// of the pool. |
| 391 | pub struct ThreadPool { |
| 392 | thread_name: Option<String>, |
| 393 | stack_size: Option<usize>, |
| 394 | concurrency_limit: usize, |
| 395 | queue: (Sender<Coroutine>, Receiver<Coroutine>), |
| 396 | immediate_queue: (Sender<Coroutine>, Receiver<Coroutine>), |
| 397 | shared: Arc<Shared>, |
| 398 | } |
| 399 | |
| 400 | impl Default for ThreadPool { |
| 401 | fn default() -> Self { |
| 402 | Self::new() |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | impl ThreadPool { |
| 407 | /// Create a new thread pool with the default configuration. |
| 408 | /// |
| 409 | /// If you'd like to customize the thread pool's behavior then use |
| 410 | /// [`ThreadPool::builder`]. |
| 411 | #[inline] |
| 412 | pub fn new() -> Self { |
| 413 | Self::builder().build() |
| 414 | } |
| 415 | |
| 416 | /// Get a builder for creating a customized thread pool. |
| 417 | #[inline] |
| 418 | pub fn builder() -> Builder { |
| 419 | Builder::default() |
| 420 | } |
| 421 | |
| 422 | /// Get the number of threads currently running in the thread pool. |
| 423 | pub fn threads(&self) -> usize { |
| 424 | *self.shared.thread_count.lock().unwrap() |
| 425 | } |
| 426 | |
| 427 | /// Get the number of tasks queued for execution, but not yet started. |
| 428 | /// |
| 429 | /// This number will always be less than or equal to the configured |
| 430 | /// [`queue_limit`](Builder::queue_limit), if any. |
| 431 | /// |
| 432 | /// Note that the number returned may become immediately outdated after |
| 433 | /// invocation. |
| 434 | /// |
| 435 | /// # Examples |
| 436 | /// |
| 437 | /// ``` |
| 438 | /// use std::{thread::sleep, time::Duration}; |
| 439 | /// |
| 440 | /// // Create a pool with just one thread. |
| 441 | /// let pool = threadfin::builder().size(1).build(); |
| 442 | /// |
| 443 | /// // Nothing is queued yet. |
| 444 | /// assert_eq!(pool.queued_tasks(), 0); |
| 445 | /// |
| 446 | /// // Start a slow task. |
| 447 | /// let task = pool.execute(|| { |
| 448 | /// sleep(Duration::from_millis(100)); |
| 449 | /// }); |
| 450 | /// |
| 451 | /// // Wait a little for the task to start. |
| 452 | /// sleep(Duration::from_millis(10)); |
| 453 | /// assert_eq!(pool.queued_tasks(), 0); |
| 454 | /// |
| 455 | /// // Enqueue some more tasks. |
| 456 | /// let count = 4; |
| 457 | /// for _ in 0..count { |
| 458 | /// pool.execute(|| { |
| 459 | /// // work to do |
| 460 | /// }); |
| 461 | /// } |
| 462 | /// |
| 463 | /// // The tasks should still be in the queue because the slow task is |
| 464 | /// // running on the only thread. |
| 465 | /// assert_eq!(pool.queued_tasks(), count); |
| 466 | /// # pool.join(); |
| 467 | /// ``` |
| 468 | #[inline] |
| 469 | pub fn queued_tasks(&self) -> usize { |
| 470 | self.queue.0.len() |
| 471 | } |
| 472 | |
| 473 | /// Get the number of tasks currently running. |
| 474 | /// |
| 475 | /// Note that the number returned may become immediately outdated after |
| 476 | /// invocation. |
| 477 | /// |
| 478 | /// # Examples |
| 479 | /// |
| 480 | /// ``` |
| 481 | /// use std::{thread::sleep, time::Duration}; |
| 482 | /// |
| 483 | /// let pool = threadfin::ThreadPool::new(); |
| 484 | /// |
| 485 | /// // Nothing is running yet. |
| 486 | /// assert_eq!(pool.running_tasks(), 0); |
| 487 | /// |
| 488 | /// // Start a task. |
| 489 | /// let task = pool.execute(|| { |
| 490 | /// sleep(Duration::from_millis(100)); |
| 491 | /// }); |
| 492 | /// |
| 493 | /// // Wait a little for the task to start. |
| 494 | /// sleep(Duration::from_millis(10)); |
| 495 | /// assert_eq!(pool.running_tasks(), 1); |
| 496 | /// |
| 497 | /// // Wait for the task to complete. |
| 498 | /// task.join(); |
| 499 | /// assert_eq!(pool.running_tasks(), 0); |
| 500 | /// ``` |
| 501 | #[inline] |
| 502 | pub fn running_tasks(&self) -> usize { |
| 503 | self.shared.running_tasks_count.load(Ordering::Relaxed) |
| 504 | } |
| 505 | |
| 506 | /// Get the number of tasks completed (successfully or otherwise) by this |
| 507 | /// pool since it was created. |
| 508 | /// |
| 509 | /// Note that the number returned may become immediately outdated after |
| 510 | /// invocation. |
| 511 | /// |
| 512 | /// # Examples |
| 513 | /// |
| 514 | /// ``` |
| 515 | /// let pool = threadfin::ThreadPool::new(); |
| 516 | /// assert_eq!(pool.completed_tasks(), 0); |
| 517 | /// |
| 518 | /// pool.execute(|| 2 + 2).join(); |
| 519 | /// assert_eq!(pool.completed_tasks(), 1); |
| 520 | /// |
| 521 | /// pool.execute(|| 2 + 2).join(); |
| 522 | /// assert_eq!(pool.completed_tasks(), 2); |
| 523 | /// ``` |
| 524 | #[inline] |
| 525 | #[allow(clippy::useless_conversion)] |
| 526 | pub fn completed_tasks(&self) -> u64 { |
| 527 | self.shared.completed_tasks_count.load(Ordering::Relaxed).into() |
| 528 | } |
| 529 | |
| 530 | /// Get the number of tasks that have panicked since the pool was created. |
| 531 | /// |
| 532 | /// Note that the number returned may become immediately outdated after |
| 533 | /// invocation. |
| 534 | /// |
| 535 | /// # Examples |
| 536 | /// |
| 537 | /// ``` |
| 538 | /// use std::{thread::sleep, time::Duration}; |
| 539 | /// |
| 540 | /// let pool = threadfin::ThreadPool::new(); |
| 541 | /// assert_eq!(pool.panicked_tasks(), 0); |
| 542 | /// |
| 543 | /// let task = pool.execute(|| { |
| 544 | /// panic!("this task panics"); |
| 545 | /// }); |
| 546 | /// |
| 547 | /// while !task.is_done() { |
| 548 | /// sleep(Duration::from_millis(100)); |
| 549 | /// } |
| 550 | /// |
| 551 | /// assert_eq!(pool.panicked_tasks(), 1); |
| 552 | /// ``` |
| 553 | #[inline] |
| 554 | #[allow(clippy::useless_conversion)] |
| 555 | pub fn panicked_tasks(&self) -> u64 { |
| 556 | self.shared.panicked_tasks_count.load(Ordering::SeqCst).into() |
| 557 | } |
| 558 | |
| 559 | /// Submit a closure to be executed by the thread pool. |
| 560 | /// |
| 561 | /// If all worker threads are busy, but there are less threads than the |
| 562 | /// configured maximum, an additional thread will be created and added to |
| 563 | /// the pool to execute this task. |
| 564 | /// |
| 565 | /// If all worker threads are busy and the pool has reached the configured |
| 566 | /// maximum number of threads, the task will be enqueued. If the queue is |
| 567 | /// configured with a limit, this call will block until space becomes |
| 568 | /// available in the queue. |
| 569 | /// |
| 570 | /// # Examples |
| 571 | /// |
| 572 | /// ``` |
| 573 | /// let pool = threadfin::ThreadPool::new(); |
| 574 | /// let task = pool.execute(|| { |
| 575 | /// 2 + 2 // some expensive computation |
| 576 | /// }); |
| 577 | /// |
| 578 | /// // do something in the meantime |
| 579 | /// |
| 580 | /// // now wait for the result |
| 581 | /// let sum = task.join(); |
| 582 | /// assert_eq!(sum, 4); |
| 583 | /// ``` |
| 584 | pub fn execute<T, F>(&self, closure: F) -> Task<T> |
| 585 | where |
| 586 | T: Send + 'static, |
| 587 | F: FnOnce() -> T + Send + 'static, |
| 588 | { |
| 589 | let (task, coroutine) = Task::from_closure(closure); |
| 590 | |
| 591 | self.execute_coroutine(coroutine); |
| 592 | |
| 593 | task |
| 594 | } |
| 595 | |
| 596 | /// Submit a future to be executed by the thread pool. |
| 597 | /// |
| 598 | /// If all worker threads are busy, but there are less threads than the |
| 599 | /// configured maximum, an additional thread will be created and added to |
| 600 | /// the pool to execute this task. |
| 601 | /// |
| 602 | /// If all worker threads are busy and the pool has reached the configured |
| 603 | /// maximum number of threads, the task will be enqueued. If the queue is |
| 604 | /// configured with a limit, this call will block until space becomes |
| 605 | /// available in the queue. |
| 606 | /// |
| 607 | /// # Thread locality |
| 608 | /// |
| 609 | /// While the given future must implement [`Send`] to be moved into a thread |
| 610 | /// in the pool to be processed, once the future is assigned a thread it |
| 611 | /// will stay assigned to that single thread until completion. This improves |
| 612 | /// cache locality even across `.await` points in the future. |
| 613 | /// |
| 614 | /// ``` |
| 615 | /// let pool = threadfin::ThreadPool::new(); |
| 616 | /// let task = pool.execute_future(async { |
| 617 | /// 2 + 2 // some asynchronous code |
| 618 | /// }); |
| 619 | /// |
| 620 | /// // do something in the meantime |
| 621 | /// |
| 622 | /// // now wait for the result |
| 623 | /// let sum = task.join(); |
| 624 | /// assert_eq!(sum, 4); |
| 625 | /// ``` |
| 626 | pub fn execute_future<T, F>(&self, future: F) -> Task<T> |
| 627 | where |
| 628 | T: Send + 'static, |
| 629 | F: Future<Output = T> + Send + 'static, |
| 630 | { |
| 631 | let (task, coroutine) = Task::from_future(future); |
| 632 | |
| 633 | self.execute_coroutine(coroutine); |
| 634 | |
| 635 | task |
| 636 | } |
| 637 | |
| 638 | /// Attempts to execute a closure on the thread pool without blocking. |
| 639 | /// |
| 640 | /// If the pool is at its max thread count and the task queue is full, the |
| 641 | /// task is rejected and an error is returned. The original closure can be |
| 642 | /// extracted from the error. |
| 643 | /// |
| 644 | /// # Examples |
| 645 | /// |
| 646 | /// One use for this method is implementing backpressure by executing a |
| 647 | /// closure on the current thread if a pool is currently full. |
| 648 | /// |
| 649 | /// ``` |
| 650 | /// let pool = threadfin::ThreadPool::new(); |
| 651 | /// |
| 652 | /// // Try to run a closure in the thread pool. |
| 653 | /// let result = pool.try_execute(|| 2 + 2) |
| 654 | /// // If successfully submitted, block until the task completes. |
| 655 | /// .map(|task| task.join()) |
| 656 | /// // If the pool was full, invoke the closure here and now. |
| 657 | /// .unwrap_or_else(|error| error.into_inner()()); |
| 658 | /// |
| 659 | /// assert_eq!(result, 4); |
| 660 | /// ``` |
| 661 | pub fn try_execute<T, F>(&self, closure: F) -> Result<Task<T>, PoolFullError<F>> |
| 662 | where |
| 663 | T: Send + 'static, |
| 664 | F: FnOnce() -> T + Send + 'static, |
| 665 | { |
| 666 | let (task, coroutine) = Task::from_closure(closure); |
| 667 | |
| 668 | self.try_execute_coroutine(coroutine) |
| 669 | .map(|_| task) |
| 670 | .map_err(|coroutine| PoolFullError(coroutine.into_inner_closure())) |
| 671 | } |
| 672 | |
| 673 | /// Attempts to execute a future on the thread pool without blocking. |
| 674 | /// |
| 675 | /// If the pool is at its max thread count and the task queue is full, the |
| 676 | /// task is rejected and an error is returned. The original future can be |
| 677 | /// extracted from the error. |
| 678 | pub fn try_execute_future<T, F>(&self, future: F) -> Result<Task<T>, PoolFullError<F>> |
| 679 | where |
| 680 | T: Send + 'static, |
| 681 | F: Future<Output = T> + Send + 'static, |
| 682 | { |
| 683 | let (task, coroutine) = Task::from_future(future); |
| 684 | |
| 685 | self.try_execute_coroutine(coroutine) |
| 686 | .map(|_| task) |
| 687 | .map_err(|coroutine| PoolFullError(coroutine.into_inner_future())) |
| 688 | } |
| 689 | |
| 690 | fn execute_coroutine(&self, coroutine: Coroutine) { |
| 691 | if let Err(coroutine) = self.try_execute_coroutine(coroutine) { |
| 692 | // Cannot fail because we hold a reference to both the channel |
| 693 | // sender and receiver and it cannot be closed here. |
| 694 | self.queue.0.send(coroutine).unwrap(); |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | fn try_execute_coroutine(&self, coroutine: Coroutine) -> Result<(), Coroutine> { |
| 699 | // First, try to pass the coroutine to an idle worker currently polling |
| 700 | // for work. This is the most favorable scenario for a task to begin |
| 701 | // processing. |
| 702 | if let Err(e) = self.immediate_queue.0.try_send(coroutine) { |
| 703 | // Error means no workers are currently polling the queue. |
| 704 | debug_assert!(!e.is_disconnected()); |
| 705 | |
| 706 | // If possible, spawn an additional thread to handle the task. |
| 707 | if let Err(e) = self.spawn_thread(Some(e.into_inner())) { |
| 708 | // Finally as a last resort, enqueue the task into the queue, |
| 709 | // but only if it isn't full. |
| 710 | if let Err(e) = self.queue.0.try_send(e.unwrap()) { |
| 711 | return Err(e.into_inner()); |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | Ok(()) |
| 717 | } |
| 718 | |
| 719 | /// Shut down this thread pool and block until all existing tasks have |
| 720 | /// completed and threads have stopped. |
| 721 | pub fn join(self) { |
| 722 | self.join_internal(None); |
| 723 | } |
| 724 | |
| 725 | /// Shut down this thread pool and block until all existing tasks have |
| 726 | /// completed and threads have stopped, or until the given timeout passes. |
| 727 | /// |
| 728 | /// Returns `true` if the thread pool shut down fully before the timeout. |
| 729 | pub fn join_timeout(self, timeout: Duration) -> bool { |
| 730 | self.join_deadline(Instant::now() + timeout) |
| 731 | } |
| 732 | |
| 733 | /// Shut down this thread pool and block until all existing tasks have |
| 734 | /// completed and threads have stopped, or the given deadline passes. |
| 735 | /// |
| 736 | /// Returns `true` if the thread pool shut down fully before the deadline. |
| 737 | pub fn join_deadline(self, deadline: Instant) -> bool { |
| 738 | self.join_internal(Some(deadline)) |
| 739 | } |
| 740 | |
| 741 | fn join_internal(self, deadline: Option<Instant>) -> bool { |
| 742 | // Closing this channel will interrupt any idle workers and signal to |
| 743 | // all workers that the pool is shutting down. |
| 744 | drop(self.queue.0); |
| 745 | |
| 746 | let mut thread_count = self.shared.thread_count.lock().unwrap(); |
| 747 | |
| 748 | while *thread_count > 0 { |
| 749 | // If a deadline is set, figure out how much time is remaining and |
| 750 | // wait for that amount. |
| 751 | if let Some(deadline) = deadline { |
| 752 | if let Some(timeout) = deadline.checked_duration_since(Instant::now()) { |
| 753 | thread_count = self |
| 754 | .shared |
| 755 | .shutdown_cvar |
| 756 | .wait_timeout(thread_count, timeout) |
| 757 | .unwrap() |
| 758 | .0; |
| 759 | } else { |
| 760 | return false; |
| 761 | } |
| 762 | } |
| 763 | // If a deadline is not set, wait forever. |
| 764 | else { |
| 765 | thread_count = self.shared.shutdown_cvar.wait(thread_count).unwrap(); |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | true |
| 770 | } |
| 771 | |
| 772 | /// Spawn an additional thread into the thread pool, if possible. |
| 773 | /// |
| 774 | /// If an initial thunk is given, it will be the first thunk the thread |
| 775 | /// executes once ready for work. |
| 776 | fn spawn_thread(&self, initial_task: Option<Coroutine>) -> Result<(), Option<Coroutine>> { |
| 777 | struct WorkerListener { |
| 778 | shared: Arc<Shared>, |
| 779 | } |
| 780 | |
| 781 | impl Listener for WorkerListener { |
| 782 | fn on_task_started(&mut self) { |
| 783 | self.shared |
| 784 | .running_tasks_count |
| 785 | .fetch_add(1, Ordering::Relaxed); |
| 786 | } |
| 787 | |
| 788 | fn on_task_completed(&mut self, panicked: bool) { |
| 789 | self.shared |
| 790 | .running_tasks_count |
| 791 | .fetch_sub(1, Ordering::Relaxed); |
| 792 | self.shared |
| 793 | .completed_tasks_count |
| 794 | .fetch_add(1, Ordering::Relaxed); |
| 795 | |
| 796 | if panicked { |
| 797 | self.shared |
| 798 | .panicked_tasks_count |
| 799 | .fetch_add(1, Ordering::SeqCst); |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | fn on_idle(&mut self) -> bool { |
| 804 | // Check if the worker should shut down by seeing if we are over |
| 805 | // the minimum worker count. |
| 806 | *self.shared.thread_count.lock().unwrap() > self.shared.min_threads |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | impl Drop for WorkerListener { |
| 811 | fn drop(&mut self) { |
| 812 | if let Ok(mut count) = self.shared.thread_count.lock() { |
| 813 | *count = count.saturating_sub(1); |
| 814 | self.shared.shutdown_cvar.notify_all(); |
| 815 | } |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | // Lock the thread count to prevent race conditions when determining |
| 820 | // whether new threads can be created. |
| 821 | let mut thread_count = self.shared.thread_count.lock().unwrap(); |
| 822 | |
| 823 | // We've reached the configured limit for threads, do nothing. |
| 824 | if *thread_count >= self.shared.max_threads { |
| 825 | return Err(initial_task); |
| 826 | } |
| 827 | |
| 828 | // Configure the thread based on the thread pool configuration. |
| 829 | let mut builder = thread::Builder::new(); |
| 830 | |
| 831 | if let Some(name) = self.thread_name.as_ref() { |
| 832 | builder = builder.name(name.clone()); |
| 833 | } |
| 834 | |
| 835 | if let Some(size) = self.stack_size { |
| 836 | builder = builder.stack_size(size); |
| 837 | } |
| 838 | |
| 839 | *thread_count += 1; |
| 840 | |
| 841 | let worker = Worker::new( |
| 842 | initial_task, |
| 843 | self.queue.1.clone(), |
| 844 | self.immediate_queue.1.clone(), |
| 845 | self.concurrency_limit, |
| 846 | self.shared.keep_alive, |
| 847 | WorkerListener { |
| 848 | shared: self.shared.clone(), |
| 849 | }, |
| 850 | ); |
| 851 | |
| 852 | // We can now safely unlock the thread count since the worker struct |
| 853 | // will decrement the count again if it is dropped. |
| 854 | drop(thread_count); |
| 855 | |
| 856 | builder.spawn(move || worker.run()).unwrap(); |
| 857 | |
| 858 | Ok(()) |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | impl fmt::Debug for ThreadPool { |
| 863 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 864 | f.debug_struct("ThreadPool") |
| 865 | .field("queued_tasks", &self.queued_tasks()) |
| 866 | .field("running_tasks", &self.running_tasks()) |
| 867 | .field("completed_tasks", &self.completed_tasks()) |
| 868 | .finish() |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | /// Thread pool state shared by the owner and the worker threads. |
| 873 | struct Shared { |
| 874 | min_threads: usize, |
| 875 | max_threads: usize, |
| 876 | thread_count: Mutex<usize>, |
| 877 | running_tasks_count: AtomicUsize, |
| 878 | completed_tasks_count: AtomicCounter, |
| 879 | panicked_tasks_count: AtomicCounter, |
| 880 | keep_alive: Duration, |
| 881 | shutdown_cvar: Condvar, |
| 882 | } |