diff options
Diffstat (limited to 'hello_server/src/lib.rs')
-rw-r--r-- | hello_server/src/lib.rs | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/hello_server/src/lib.rs b/hello_server/src/lib.rs new file mode 100644 index 0000000..c8e6a3e --- /dev/null +++ b/hello_server/src/lib.rs @@ -0,0 +1,88 @@ +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::mpsc; +use std::thread; + +trait FnBox { + fn call_box(self: Box<Self>); +} + +impl <F: FnOnce()> FnBox for F { + fn call_box(self: Box<F>) { + (*self)() + } +} + +type Job = Box<FnBox + Send + 'static>; + +pub struct ThreadPool { + workers: Vec<Worker>, + sender: mpsc::Sender<Job>, +} + +impl ThreadPool { + pub fn new(size: usize) -> Result<ThreadPool, &'static str> { + if size <= 0 { + return Err("failed to create pool"); + } + + 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))?); + } + + Ok(ThreadPool { + workers, + sender, + }) + } + + pub fn spawn<F, T>(f: F) -> thread::JoinHandle<T> + where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static + { + thread::spawn(f) + } + + pub fn execute<F>(&self, f: F) + where + F: FnOnce() + Send + 'static + { + let job = Box::new(f); + self.sender.send(job).unwrap(); + } + +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) + -> Result<Worker, &'static str> + { + let thread = thread::spawn(move || { + loop { + let job = receiver + .lock().expect("lock poisoned!") + .recv().unwrap(); + println!("worker {} got job; executing...", id); + + job.call_box(); + } + }); + + Ok(Worker { + id, + thread, + }) + } +} |