Expand description
A simple thread pool to execute jobs in parallel
A simple crate without dependencies which allows you to create a threadpool that has a specified amount of threads which execute given jobs. Threads don’t crash when a job panics!
§Examples
§Basic usage
A basic use of the threadpool
use easy_threadpool::ThreadPoolBuilder;
fn job() {
println!("Hello world!");
}
let builder = ThreadPoolBuilder::with_max_threads()?;
let pool = builder.build()?;
for _ in 0..10 {
pool.send_job(job);
}
assert!(pool.wait_until_finished().is_ok());
§More advanced usage
A slightly more advanced usage of the threadpool
use easy_threadpool::ThreadPoolBuilder;
use std::sync::mpsc::channel;
let builder = ThreadPoolBuilder::with_max_threads()?;
let pool = builder.build()?;
let (tx, rx) = channel();
for _ in 0..10 {
let tx = tx.clone();
pool.send_job(move || {
tx.send(1).expect("Receiver should still exist");
});
}
assert!(pool.wait_until_finished().is_ok());
assert_eq!(rx.iter().take(10).fold(0, |a, b| a + b), 10);
§Dealing with panics
This threadpool implementation is resistant to jobs panicing
use easy_threadpool::ThreadPoolBuilder;
use std::sync::mpsc::channel;
use std::num::NonZeroUsize;
fn panic_fn() {
panic!("Test panic");
}
let num = NonZeroUsize::try_from(1)?;
let builder = ThreadPoolBuilder::with_thread_amount(num);
let pool = builder.build()?;
let (tx, rx) = channel();
for _ in 0..10 {
let tx = tx.clone();
pool.send_job(move || {
tx.send(1).expect("Receiver should still exist");
panic!("Test panic");
});
}
assert!(pool.wait_until_finished().is_err());
pool.wait_until_finished_unchecked();
assert_eq!(pool.jobs_paniced(), 10);
assert_eq!(rx.iter().take(10).fold(0, |a, b| a + b), 10);
Structs§
- JobHas
Paniced Error - Simple error to indicate that a job has paniced in the threadpool
- Thread
Pool - Threadpool abstraction to keep some state
- Thread
Pool Builder - A ThreadPoolbuilder is a builder to easily create a thread pool