Browse Source

Allow termination of workers

master
Noelle 4 years ago
parent
commit
620869dbe8
2 changed files with 40 additions and 13 deletions
  1. 38
    13
      src/lib.rs
  2. 2
    0
      src/main.rs

+ 38
- 13
src/lib.rs View File

@@ -1,9 +1,14 @@
use std::thread;
use std::sync::{mpsc, Mutex, Arc};

enum Message {
NewJob(Job),
Terminate
}

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

type Job = Box<dyn FnOnce() + Send + 'static>;
@@ -28,12 +33,13 @@ impl ThreadPool {
}

}

pub fn execute<F>(&self, f: F)
where F: FnOnce() + Send + 'static
where
F: FnOnce() + Send + 'static
{
let job = Box::new(f);
self.sender.send(job).unwrap();

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

// pub fn spawn<F, T>(f: F) -> JoinHandle<T>
@@ -48,34 +54,53 @@ impl ThreadPool {

impl Drop for ThreadPool {
fn drop(&mut self) {
println!("Sending terminate message to all workers.");
for _ in &mut self.workers {
self.sender.send(Message::Terminate).unwrap();
}
println!("Shutting down all workers.");

for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
println!("Shutting down worker {}.", worker.id);

worker.thread.join().unwrap();
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 {
let thread = thread::spawn(move || {
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();

match message {
Message::NewJob(job) => {
println!("Worker {} got a job; executing.", id);

println!("Worker {} got a job, executing.", id);
job();
},
Message::Terminate => {
println!("Worker {} was told to terminate.", id);

job();
break;
},
}
}
});

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

+ 2
- 0
src/main.rs View File

@@ -16,6 +16,8 @@ fn main() {
handle_connection(stream);
});
}

println!("Shutting down.");
}

fn handle_connection(mut stream: TcpStream) {

Loading…
Cancel
Save