workerpool_rs/lib.rs
1//! ## Worker Pool
2//!
3//! This module contains constructs for dealing with concurrent tasks. It can spawn
4//! any number of worker threads and sync them with other channels.
5//!
6//! ## Examples
7//!
8//! ### Synchronized with other channels
9//!
10//! ```
11//! use workerpool_rs::pool::WorkerPool;
12//! use std::sync::mpsc::channel;
13//! use std::sync::{Arc, Mutex};
14//!
15//! let n_workers = 4;
16//! let n_jobs = 8;
17//! let pool = WorkerPool::new(n_workers);
18//!
19//! let (tx, rx) = channel();
20//! let atx = Arc::new(Mutex::new(tx));
21//! for _ in 0..n_jobs {
22//! let atx = atx.clone();
23//! pool.execute(move|| {
24//! let tx = atx.lock().unwrap();
25//! tx.send(1).expect("channel will be there waiting for the pool");
26//! });
27//! }
28//!
29//! assert_eq!(rx.iter().take(n_jobs).fold(0, |a, b| a + b), 8);
30//!```
31//!
32//! ### Sinchronized with Barrier
33//!```
34//!
35//! use std::sync::atomic::{AtomicUsize, Ordering};
36//! use std::sync::{Arc, Barrier};
37//! use workerpool_rs::pool::WorkerPool;
38//!
39//! let n_workers = 42;
40//! let n_jobs = 23;
41//! let pool = WorkerPool::new(n_workers);
42//! let an_atomic = Arc::new(AtomicUsize::new(0));
43//!
44//! assert!(n_jobs <= n_workers, "too many jobs, will deadlock");
45//!
46//! let barrier = Arc::new(Barrier::new(n_jobs + 1));
47//! for _ in 0..n_jobs {
48//! let barrier = barrier.clone();
49//! let an_atomic = an_atomic.clone();
50//!
51//! pool.execute(move|| {
52//! // do the heavy work
53//! an_atomic.fetch_add(1, Ordering::Relaxed);
54//!
55//! // then wait for the other threads
56//! barrier.wait();
57//! });
58//! }
59//!
60//! barrier.wait();
61//! assert_eq!(an_atomic.load(Ordering::SeqCst), /* n_jobs = */ 23);
62//!```
63
64// Imports and makes pool public.
65pub mod pool;