yup the guard was guarded

This commit is contained in:
Quaternions 2023-10-04 03:37:52 -07:00
parent 77d060b90c
commit 9df4da9d26

View File

@ -1,6 +1,6 @@
use std::thread; use std::thread;
use std::sync::{mpsc,Arc}; use std::sync::{mpsc,Arc};
use parking_lot::{Mutex,Condvar}; use parking_lot::Mutex;
//The goal here is to have a worker thread that parks itself when it runs out of work. //The goal here is to have a worker thread that parks itself when it runs out of work.
//The worker thread publishes the result of its work back to the worker object for every item in the work queue. //The worker thread publishes the result of its work back to the worker object for every item in the work queue.
@ -8,7 +8,7 @@ use parking_lot::{Mutex,Condvar};
struct Worker<Task:Send,Value:Clone> { struct Worker<Task:Send,Value:Clone> {
sender: mpsc::Sender<Task>, sender: mpsc::Sender<Task>,
receiver: Arc<(Mutex<mpsc::Receiver<Task>>,Condvar)>, receiver: Arc<Mutex<mpsc::Receiver<Task>>>,
value:Arc<Mutex<Value>>, value:Arc<Mutex<Value>>,
} }
@ -17,15 +17,14 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
let (sender, receiver) = mpsc::channel::<Task>(); let (sender, receiver) = mpsc::channel::<Task>();
let ret=Self { let ret=Self {
sender, sender,
receiver:Arc::new((Mutex::new(receiver),Condvar::new())), receiver:Arc::new(Mutex::new(receiver)),
value:Arc::new(Mutex::new(value)), value:Arc::new(Mutex::new(value)),
}; };
let receiver=ret.receiver.clone(); let receiver=ret.receiver.clone();
let value=ret.value.clone(); let value=ret.value.clone();
thread::spawn(move || { thread::spawn(move || {
loop { loop {
loop { match receiver.lock().recv() {
match receiver.0.lock().recv() {
Ok(task) => { Ok(task) => {
println!("Worker got a task"); println!("Worker got a task");
// Process the task // Process the task
@ -37,16 +36,12 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
} }
} }
} }
receiver.1.wait(&mut receiver.0.lock());
}
}); });
ret ret
} }
fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{ fn send(&self,task:Task)->Result<(), mpsc::SendError<Task>>{
let ret=self.sender.send(task); self.sender.send(task)
self.receiver.1.notify_one();
ret
} }
fn grab_clone(&self)->Value{ fn grab_clone(&self)->Value{
@ -54,7 +49,7 @@ impl<Task:Send+'static,Value:Clone+Send+'static> Worker<Task,Value> {
} }
} }
#[test] #[test]//How to run this test with printing: cargo test --release -- --nocapture
fn test_worker() { fn test_worker() {
println!("hiiiii"); println!("hiiiii");
// Create the worker thread // Create the worker thread
@ -85,4 +80,7 @@ fn test_worker() {
worker.send(task).unwrap(); worker.send(task).unwrap();
println!("value={:?}",worker.grab_clone()); println!("value={:?}",worker.grab_clone());
// wait long enough to see print from final task
thread::sleep(std::time::Duration::from_secs(1));
} }