2023-10-04 08:30:33 +00:00
|
|
|
use std::thread;
|
2023-10-04 08:55:44 +00:00
|
|
|
use std::sync::{mpsc,Arc};
|
|
|
|
use parking_lot::{Mutex,Condvar};
|
2023-10-04 08:30:33 +00:00
|
|
|
|
2023-10-04 09:58:02 +00:00
|
|
|
struct Worker<Task:Send> {
|
|
|
|
sender: mpsc::Sender<Task>,
|
|
|
|
receiver: Arc<(Mutex<mpsc::Receiver<Task>>,Condvar)>,
|
2023-10-04 08:30:33 +00:00
|
|
|
}
|
|
|
|
|
2023-10-04 09:58:02 +00:00
|
|
|
impl<Task:Send+'static> Worker<Task> {
|
|
|
|
fn new() -> Self {
|
|
|
|
let (sender, receiver) = mpsc::channel::<Task>();
|
|
|
|
Self {
|
|
|
|
sender,
|
|
|
|
receiver:Arc::new((Mutex::new(receiver),Condvar::new())),
|
|
|
|
}
|
2023-10-04 08:30:33 +00:00
|
|
|
}
|
|
|
|
|
2023-10-04 09:58:02 +00:00
|
|
|
fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
|
|
|
|
let ret=self.sender.send(task);
|
|
|
|
self.receiver.1.notify_one();
|
|
|
|
ret
|
|
|
|
}
|
|
|
|
|
|
|
|
fn start(&self) {
|
|
|
|
let receiver=self.receiver.clone();
|
2023-10-04 08:30:33 +00:00
|
|
|
thread::spawn(move || {
|
2023-10-04 09:58:02 +00:00
|
|
|
loop{
|
|
|
|
loop {
|
|
|
|
match receiver.0.lock().recv() {
|
|
|
|
Ok(_task) => {
|
|
|
|
println!("Worker got a task");
|
|
|
|
// Process the task
|
|
|
|
}
|
|
|
|
Err(_) => {
|
|
|
|
println!("Worker stopping.",);
|
|
|
|
break;
|
|
|
|
}
|
2023-10-04 08:30:33 +00:00
|
|
|
}
|
|
|
|
}
|
2023-10-04 09:58:02 +00:00
|
|
|
receiver.1.wait(&mut receiver.0.lock());
|
2023-10-04 08:30:33 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-04 09:22:45 +00:00
|
|
|
#[test]
|
|
|
|
fn test_worker() {
|
2023-10-04 08:30:33 +00:00
|
|
|
|
2023-10-04 08:57:18 +00:00
|
|
|
// Create the worker thread
|
2023-10-04 09:58:02 +00:00
|
|
|
let worker = Worker::new();
|
2023-10-04 08:30:33 +00:00
|
|
|
|
2023-10-04 08:57:18 +00:00
|
|
|
// Start the worker thread
|
2023-10-04 08:30:33 +00:00
|
|
|
worker.start();
|
|
|
|
|
2023-10-04 08:57:18 +00:00
|
|
|
// Send tasks to the worker
|
2023-10-04 08:30:33 +00:00
|
|
|
for i in 0..5 {
|
2023-10-04 09:58:02 +00:00
|
|
|
let task = crate::instruction::TimedInstruction{
|
|
|
|
time:0,
|
|
|
|
instruction:crate::body::PhysicsInstruction::StrafeTick,
|
|
|
|
};
|
|
|
|
worker.send(task).unwrap();
|
2023-10-04 08:30:33 +00:00
|
|
|
}
|
|
|
|
|
2023-10-04 08:57:18 +00:00
|
|
|
// Optional: Signal the 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:57:18 +00:00
|
|
|
// Sleep to allow the 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 09:58:02 +00:00
|
|
|
// Send a new task
|
|
|
|
let task = crate::instruction::TimedInstruction{
|
|
|
|
time:0,
|
|
|
|
instruction:crate::body::PhysicsInstruction::StrafeTick,
|
|
|
|
};
|
|
|
|
worker.send(task).unwrap();
|
2023-10-04 08:34:24 +00:00
|
|
|
}
|