strafe-client-jed/src/worker.rs

77 lines
2.3 KiB
Rust
Raw Normal View History

2023-10-04 08:30:33 +00:00
use std::thread;
use std::sync::{mpsc, Arc, Mutex};
struct Worker {
id: usize,
receiver: Arc<Mutex<mpsc::Receiver<Task>>>,
2023-10-04 08:37:01 +00:00
is_active: Arc<Mutex<bool>>,
2023-10-04 08:30:33 +00:00
}
impl Worker {
2023-10-04 08:37:01 +00:00
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Task>>>, is_active: Arc<Mutex<bool>>) -> Worker {
Worker { id, receiver, is_active }
2023-10-04 08:30:33 +00:00
}
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;
}
}
}
2023-10-04 08:37:01 +00:00
// Set is_active to false when the worker is done
*self.is_active.lock().unwrap() = false;
2023-10-04 08:30:33 +00:00
});
}
}
type Task = String;
fn main() {
let (sender, receiver) = mpsc::channel::<Task>();
let receiver = Arc::new(Mutex::new(receiver));
2023-10-04 08:37:01 +00:00
let is_active = Arc::new(Mutex::new(true));
2023-10-04 08:30:33 +00:00
2023-10-04 08:37:01 +00:00
// Create the first worker thread
let worker = Worker::new(1, Arc::clone(&receiver), Arc::clone(&is_active));
2023-10-04 08:30:33 +00:00
2023-10-04 08:37:01 +00:00
// Start the first worker thread
2023-10-04 08:30:33 +00:00
worker.start();
2023-10-04 08:37:01 +00:00
// Send tasks to the first worker
2023-10-04 08:30:33 +00:00
for i in 0..5 {
let task = format!("Task {}", i);
sender.send(task).unwrap();
}
2023-10-04 08:37:01 +00:00
// Optional: Signal the first worker to stop (in a real-world scenario)
2023-10-04 08:30:33 +00:00
// sender.send("STOP".to_string()).unwrap();
2023-10-04 08:37:01 +00:00
// Sleep to allow the first worker thread to finish processing
2023-10-04 08:30:33 +00:00
thread::sleep(std::time::Duration::from_secs(2));
2023-10-04 08:34:24 +00:00
2023-10-04 08:37:01 +00:00
// Check if the first worker is still active
let is_first_worker_active = *is_active.lock().unwrap();
2023-10-04 08:34:24 +00:00
2023-10-04 08:37:01 +00:00
if !is_first_worker_active {
// If the first worker is done, spawn a new worker
let new_worker = Worker::new(2, Arc::clone(&receiver), Arc::clone(&is_active));
new_worker.start();
sender.send("New Task".to_string()).unwrap();
// Sleep to allow the new worker thread to process the task
thread::sleep(std::time::Duration::from_secs(2));
} else {
println!("First worker is still active. Skipping new worker.");
}
2023-10-04 08:34:24 +00:00
}