Skip to content

Commit

Permalink
update threadppol for rustws
Browse files Browse the repository at this point in the history
  • Loading branch information
deepu105 committed Dec 3, 2020
1 parent 620b20e commit fabbcfe
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions rustws/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ use std::thread;

pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
sender: mpsc::Sender<Message>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

enum Message {
NewJob(Job),
Terminate,
}

impl ThreadPool {
/// Create a new ThreadPool.
///
Expand Down Expand Up @@ -40,25 +45,47 @@ impl ThreadPool {
{
let job = Box::new(f);

self.sender.send(job).unwrap();
self.sender.send(Message::NewJob(job)).unwrap();
}
}

impl Drop for ThreadPool {
fn drop(&mut self) {
for _ in &self.workers {
self.sender.send(Message::Terminate).unwrap();
}

for worker in &mut self.workers {
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}

struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
let message = receiver.lock().unwrap().recv().unwrap();

// println!("Worker {} got a job; executing.", id);

job();
match message {
Message::NewJob(job) => {
job();
}
Message::Terminate => {
break;
}
}
});

Worker { id, thread }
Worker {
id,
thread: Some(thread),
}
}
}

0 comments on commit fabbcfe

Please sign in to comment.