Implement basic multithreaded command execution

This commit is contained in:
William Brawner 2022-07-24 21:32:40 -06:00
parent 6e7d8e807f
commit ab612dcfd9
2 changed files with 86 additions and 1 deletions

80
src/lib.rs Normal file
View file

@ -0,0 +1,80 @@
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(Message::NewJob(job)).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
println!("Sending terminate message to all workers");
for _ in &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);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
enum Message {
NewJob(Job),
Terminate,
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv().unwrap();
match message {
Message::NewJob(job) => {
println!("Worker {} got a job; executing", id);
job();
}
Message::Terminate => {
println!("Worker {} was told to terminate", id);
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}

View file

@ -8,11 +8,16 @@ use std::net::TcpStream;
use std::path::Path;
use std::process::Command;
use gsm_agent::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:4762").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
pool.execute(|| {
handle_connection(stream);
});
}
}