Compare commits

..

No commits in common. "28368bce3dcc284ccadc622164899c942253e86c" and "92b4db36a6813878d1b5dbd790f59de90acd0eea" have entirely different histories.

View file

@ -1,9 +1,3 @@
//! 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;
@ -11,7 +5,6 @@ use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
/// Error types
#[derive(Debug)]
pub enum ThreadPoolError {
PoolCreationError,
@ -40,42 +33,12 @@ 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);
@ -89,16 +52,6 @@ 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,
@ -108,9 +61,7 @@ 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();
@ -127,7 +78,7 @@ impl Drop for ThreadPool {
}
}
struct Worker {
pub struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}