From fde80830e3afd572dd2f584c6921f3f9859b7d4c Mon Sep 17 00:00:00 2001 From: Brad Clawsie Date: Thu, 3 Dec 2026 14:53:49 -0600 Subject: fix: learn_23 commit d311e19884cf647e5be3dcd935127e2386e139e0 Author: Brad Clawsie Date: Thu Dec 3 14:52:39 2026 -0600 wip: learn_23 commit 0026dc6bd00658cd881ef58672c50d599ceaf12f Author: Brad Clawsie Date: Thu Dec 3 13:54:41 2026 -0600 wip: learn_23 commit 1d7971590fc92245299e7c3f369d13f693b56af1 Author: Brad Clawsie Date: Thu Dec 3 09:22:34 2026 -0600 wip: learn_23 commit 5a2fe1a4c3c836a27c6dfbef8330bcc700a8d95b Author: Brad Clawsie Date: Thu Dec 3 08:16:56 2026 -0600 wip: learn_23 --- learn_23/src/lib.rs | 1 + learn_23/src/main.rs | 3 +++ learn_23/src/pool.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 learn_23/src/lib.rs create mode 100644 learn_23/src/main.rs create mode 100644 learn_23/src/pool.rs (limited to 'learn_23/src') diff --git a/learn_23/src/lib.rs b/learn_23/src/lib.rs new file mode 100644 index 0000000..c9e2bb1 --- /dev/null +++ b/learn_23/src/lib.rs @@ -0,0 +1 @@ +pub mod pool; diff --git a/learn_23/src/main.rs b/learn_23/src/main.rs new file mode 100644 index 0000000..db91fc6 --- /dev/null +++ b/learn_23/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + () +} diff --git a/learn_23/src/pool.rs b/learn_23/src/pool.rs new file mode 100644 index 0000000..c2fd873 --- /dev/null +++ b/learn_23/src/pool.rs @@ -0,0 +1,67 @@ +use crossbeam_channel::{unbounded, Sender, Receiver}; +use std::thread; + +pub type Job = Box; + +pub enum SubmitError { + AlreadyShutdown, +} + +pub struct WorkerPool { + pub worker_count: usize, + workers: Vec>, + sender: Option>, +} + +impl WorkerPool { + pub fn new(worker_count: usize) -> Self { + let (sender, receiver): (Sender, Receiver) = unbounded(); + + let mut workers: Vec> = Vec::with_capacity(worker_count); + for worker in 0..worker_count { + let rx = receiver.clone(); + workers.push(thread::spawn(move || { + for job in rx { + println!("worker {worker} has taken a job"); + job(); + println!("worker {worker} has completed a job"); + } + println!("worker {worker} is finished"); + })); + } + + Self { + worker_count, + workers, + sender: Some(sender), + } + } + + pub fn submit(&self, job: F) -> Result<(), SubmitError> + where + F: FnOnce() + Send + 'static + { + match &self.sender { + None => return Err(SubmitError::AlreadyShutdown), + Some(sender) => { + sender.send(Box::new(job)).unwrap(); + return Ok(()); + }, + } + } + + pub fn shutdown(&mut self) { + if self.sender.is_some() { + drop(self.sender.take()); + } + for worker in self.workers.drain(..) { + worker.join().unwrap(); + } + } +} + +impl Drop for WorkerPool { + fn drop(&mut self) { + self.shutdown() + } +} -- cgit v1.2.3