Skip to content

Commit

Permalink
graceful shutdown and clean up of server after 5 requests
Browse files Browse the repository at this point in the history
  • Loading branch information
dhanushrajgp committed Jul 13, 2024
1 parent 335ee49 commit 7692e4b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
45 changes: 36 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{

pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
sender: Option<mpsc::Sender<Job>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
Expand All @@ -27,32 +27,59 @@ impl ThreadPool {
workers.push(Worker::new(id, Arc::clone(&receiver)))
}

ThreadPool { workers, sender }
ThreadPool {
workers,
sender: Some(sender),
}
}

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

impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.sender.take());
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);

if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}

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

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

println!("Worker {id} got a job; executing....");
match message {
Ok(job) => {
println!("Worker {id} got a job; executing....");

job();
job();
}
Err(_) => {
println!("Worker {id} is shutting down....");
break;
}
}
});
Worker { id, thread }
Worker {
id,
thread: Some(thread),
}
}
}
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);

for stream in listener.incoming() {
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();

pool.execute(|| {
handle_connection(stream);
});
}

println!("Shutting down");
}

fn handle_connection(mut stream: TcpStream) {
Expand Down

0 comments on commit 7692e4b

Please sign in to comment.