Simple threadpool
My own implementation of The Rust programming langauge official book implementation of a threadpool.
Features
- Configurable pool size (single-threaded, multi-threaded, or auto-detect)
- Queue limit with backpressure - prevents unbounded memory growth
- Graceful shutdown with job completion guarantees
- Worker signaling - jobs can signal all workers to stop via
Arc<AtomicBool>
Usage
Basic Example
use ThreadPool;
// let pool = ThreadPool::new(4); // 4 workers, or 0 for auto-detect, 1 for single-threaded
let pool = default; // runs the pool while auto detecting maximum threads
pool.execute.expect;
Queue Limit with Backpressure
Prevent unbounded memory growth with configurable queue limits:
use ThreadPool;
// Default: 50,000 max jobs
let pool = new;
// Custom limit using builder pattern
let pool = new.max_jobs;
// When queue is full, execute() blocks with exponential backoff (1ms → 50ms)
for i in 0..1_000_000
Worker Signaling (Early Termination)
For scenarios like hash collision detection where one worker should stop all others:
use ThreadPool;
use ;
let pool = new;
for i in 0..1000
Or check the signal within jobs:
use ThreadPool;
use Ordering;
let pool = default;
let kill_signal = pool.get_kill_signal;
pool.execute.unwrap;
API
new(size: u8)- Create pool (0=auto, 1=single-threaded, N=N workers)max_jobs(limit: usize)- Set max queue size (builder pattern, default: 50,000)execute<F>(&self, f: F)- Execute job (blocks with backpressure when queue is full)signal_stop(&self)- Signal all workers to stop after current jobget_kill_signal(&self)- GetArc<AtomicBool>to check/set from jobsis_single_threaded(&self)- Check if single-threaded mode