thread_pool_pre 0.1.0

A Thread Pool Preview For Muti Thread to do our task.
Documentation
/*
 * @Author: axiong 
 * @Date: 2022-10-20 20:43:57
 * @LastEditors: raojianxiong 1611420064@qq.com
 * @LastEditTime: 2022-10-20 23:13:26
 * @FilePath: \web\src\lib.rs
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
use std::thread;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
///a thread poop for thread to do some task
pub struct ThreadPool{
    workers: Vec<Worker>,
    sender: mpsc::Sender<Job>,
}

impl ThreadPool{
    ///Crete a new 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(job).unwrap();
    }
}
struct Worker{
    id: usize,
    thread: thread::JoinHandle<()>,
}
type Job = Box<dyn FnBox + Send + 'static>;

impl Worker {
    fn new(id:usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker{
        let thread = thread::spawn(move || loop {
            while let Ok(job) =  receiver.lock().unwrap().recv(){
            
                println!("Worker {} got a job; excuting.", id);
                // (*job)();
                job.call_box();
            }
        });
        Worker { id, thread }
    }
}
trait FnBox{
    fn call_box(self: Box<Self>);
}
impl <F: FnOnce()> FnBox for F {
    fn call_box(self: Box<F>) {
        (*self)()
    }
}