summaryrefslogtreecommitdiff
path: root/learn_23/src/pool.rs
diff options
context:
space:
mode:
authorBrad Clawsie <brad@b7j0c.org>2026-12-03 14:53:49 -0600
committerBrad Clawsie <brad@b7j0c.org>2026-12-03 14:53:49 -0600
commitfde80830e3afd572dd2f584c6921f3f9859b7d4c (patch)
tree9e3cfbbd5eab7a28f07ed460435bd5fe8b843f93 /learn_23/src/pool.rs
parent681ca1e68560dbd6a89a0243d4a8c80b2f120ee9 (diff)
fix: learn_23
commit d311e19884cf647e5be3dcd935127e2386e139e0 Author: Brad Clawsie <brad@b7j0c.org> Date: Thu Dec 3 14:52:39 2026 -0600 wip: learn_23 commit 0026dc6bd00658cd881ef58672c50d599ceaf12f Author: Brad Clawsie <brad@b7j0c.org> Date: Thu Dec 3 13:54:41 2026 -0600 wip: learn_23 commit 1d7971590fc92245299e7c3f369d13f693b56af1 Author: Brad Clawsie <brad@b7j0c.org> Date: Thu Dec 3 09:22:34 2026 -0600 wip: learn_23 commit 5a2fe1a4c3c836a27c6dfbef8330bcc700a8d95b Author: Brad Clawsie <brad@b7j0c.org> Date: Thu Dec 3 08:16:56 2026 -0600 wip: learn_23
Diffstat (limited to 'learn_23/src/pool.rs')
-rw-r--r--learn_23/src/pool.rs67
1 files changed, 67 insertions, 0 deletions
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<dyn FnOnce() + Send + 'static>;
+
+pub enum SubmitError {
+ AlreadyShutdown,
+}
+
+pub struct WorkerPool {
+ pub worker_count: usize,
+ workers: Vec<thread::JoinHandle<()>>,
+ sender: Option<Sender<Job>>,
+}
+
+impl WorkerPool {
+ pub fn new(worker_count: usize) -> Self {
+ let (sender, receiver): (Sender<Job>, Receiver<Job>) = unbounded();
+
+ let mut workers: Vec<thread::JoinHandle<()>> = 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<F>(&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()
+ }
+}