tpool/
lib.rs

1mod error;
2mod inner;
3mod queue;
4mod worker;
5
6pub use error::JoinError;
7use inner::ThreadPoolInner;
8use std::{num::NonZeroUsize, sync::Arc};
9
10#[cfg(test)]
11mod tests;
12
13/// Job for worker
14pub type Job = Box<dyn Fn() + Send>;
15
16/// "Lazy" thread pool for executing tasks. A new thread is created only if the current
17/// number of threads is insufficient.
18#[derive(Clone)]
19pub struct ThreadPool(Arc<ThreadPoolInner>);
20
21impl ThreadPool {
22    /// Create new `ThreadPool`
23    pub fn new(max_threads: NonZeroUsize) -> Self {
24        Self(ThreadPoolInner::new(max_threads))
25    }
26
27    /// Spawn new job for thread pool
28    pub fn spawn(&self, job: impl Fn() + Send + 'static) {
29        ThreadPoolInner::spawn(&self.0, job)
30    }
31
32    /// Wait for thread pool to complete all jobs
33    pub fn join(self) -> Result<(), JoinError> {
34        self.0.join()
35    }
36}