Compare commits

...

2 commits

Author SHA1 Message Date
Augusto Dwenger J. 28368bce3d fix: Change Worker struct to be private
The Worker struct is part of the internal ThreadPool implementation and
doesn't need to be exported.
2021-01-08 19:02:51 +01:00
Augusto Dwenger J. 941b47790b doc: Add general documentation for the poolth crate 2021-01-08 19:01:57 +01:00

View file

@ -1,3 +1,9 @@
//! Small and simple ThreadPool implementation from the rust book.
//!
//! Provides an abstraction to manage multiple threads.
//! Using this abstraction will give you following advantages:
//! - Customizable pool size
//! - Graceful shutdown of the threads
use std::error::Error;
use std::fmt;
use std::sync::mpsc;
@ -5,6 +11,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
/// Error types
#[derive(Debug)]
pub enum ThreadPoolError {
PoolCreationError,
@ -33,12 +40,42 @@ enum Message {
Terminate,
}
/// The thread pool containing all workers.
///
/// # Examples
/// ```
/// use poolth::ThreadPool;
///
/// //creates a thread pool holding 4 threads.
/// let pool = ThreadPool::new(4).unwrap();
/// pool.execute(println("Hello World"))
/// ```
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
impl ThreadPool {
/// Construct a new ThreadPool using a custom size.
///
/// # Examples
/// ```
/// use poolth::ThreadPool;
///
/// //creates a thread pool holding 4 threads.
/// let pool = ThreadPool::new(4).unwrap();
/// ```
///
/// # Errors
/// Creating a new ThreadPool will return an [ThreadPoolError::PoolCreationError] if the size <= 0.
/// ```
/// use poolth::ThreadPool;
///
/// // panics due the `unwrap()` call
/// let pool = ThreadPool::new(0).unwrap();
/// // => thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: PoolCreationError'
/// ```
///
pub fn new(size: usize) -> Result<ThreadPool, ThreadPoolError> {
if size <= 0 {
return Err(ThreadPoolError::PoolCreationError);
@ -52,6 +89,16 @@ impl ThreadPool {
}
Ok(ThreadPool { workers, sender })
}
/// Run a closure in a worker of the pool.
/// # Examples
/// ```
/// use poolth::ThreadPool;
///
/// let pool = ThreadPool::new(1).unwrap();
/// pool.execute(|| println!("Hello World"))
/// ```
/// Output: `"Hello World"`
///
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
@ -61,7 +108,9 @@ impl ThreadPool {
}
}
/// For a graceful shutdown of the thread pool.
impl Drop for ThreadPool {
/// Sends a terminate message and wait until the worker is done.
fn drop(&mut self) {
for _ in &self.workers {
self.sender.send(Message::Terminate).unwrap();
@ -78,7 +127,7 @@ impl Drop for ThreadPool {
}
}
pub struct Worker {
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}