Skip to content

Commit

Permalink
implemented execute method
Browse files Browse the repository at this point in the history
  • Loading branch information
dhanushrajgp committed Jul 13, 2024
1 parent 662b32e commit 335ee49
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use std::{sync::mpsc, thread};
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};

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

type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
Expand All @@ -15,12 +18,13 @@ impl ThreadPool {
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, reciever) = mpsc::channel();
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))
workers.push(Worker::new(id, Arc::clone(&receiver)))
}

ThreadPool { workers, sender }
Expand All @@ -30,18 +34,25 @@ impl ThreadPool {
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}

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

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

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

job();
});
Worker { id, thread }
}
}

0 comments on commit 335ee49

Please sign in to comment.