From e547940f2be1f0ea0606d5847a18acf4390800a7 Mon Sep 17 00:00:00 2001 From: Quaternions Date: Wed, 4 Oct 2023 01:30:33 -0700 Subject: [PATCH] gpt --- src/worker.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/worker.rs diff --git a/src/worker.rs b/src/worker.rs new file mode 100644 index 0000000..dfdf8b0 --- /dev/null +++ b/src/worker.rs @@ -0,0 +1,56 @@ +use std::thread; +use std::sync::{mpsc, Arc, Mutex}; + +struct Worker { + id: usize, + receiver: Arc>>, +} + +impl Worker { + fn new(id: usize, receiver: Arc>>) -> Worker { + Worker { id, receiver } + } + + fn start(self) { + thread::spawn(move || { + loop { + let task = self.receiver.lock().unwrap().recv(); + match task { + Ok(task) => { + println!("Worker {} got a task: {}", self.id, task); + // Process the task + } + Err(_) => { + println!("Worker {} stopping.", self.id); + break; + } + } + } + }); + } +} + +type Task = String; + +fn main() { + let (sender, receiver) = mpsc::channel::(); + let receiver = Arc::new(Mutex::new(receiver)); + + // Create a worker thread + let worker = Worker::new(1, Arc::clone(&receiver)); + + // Start the worker thread + worker.start(); + + // Send tasks to the worker + for i in 0..5 { + let task = format!("Task {}", i); + sender.send(task).unwrap(); + } + + // Optional: Signal the worker to stop (in a real-world scenario) + // sender.send("STOP".to_string()).unwrap(); + + // Sleep to allow worker thread to finish processing + thread::sleep(std::time::Duration::from_secs(2)); +} \ No newline at end of file