6 pub struct ThreadPool
{
8 sender
: mpsc
::Sender
<Job
>,
11 type Job
= Box
<dyn FnOnce() + Send
+ '
static>;
21 /// Create a new ThreadPool.
23 /// The size is the number of threads in the pool.
27 /// The `new` function will panic if the size is zero.
28 pub fn new(size
: usize) -> ThreadPool
{
31 let (sender
, receiver
) = mpsc
::channel();
33 let receiver
= Arc
::new(Mutex
::new(receiver
));
35 let mut workers
= Vec
::with_capacity(size
);
38 workers
.push(Worker
::new(id
, Arc
::clone(&receiver
)));
41 ThreadPool { workers, sender }
44 pub fn execute
<F
>(&self, f
: F
)
46 F
: FnOnce() + Send
+ '
static,
48 let job
= Box
::new(f
);
50 self.sender
.send(job
).unwrap();
54 impl Drop
for ThreadPool
{
56 for worker
in &mut self.workers
{
57 println
!("Shutting down worker {}", worker
.id
);
59 if let Some(thread
) = worker
.thread
.take() {
60 thread
.join().unwrap();
68 thread
: Option
<thread
::JoinHandle
<()>>,
72 fn new(id
: usize, receiver
: Arc
<Mutex
<mpsc
::Receiver
<Job
>>>) -> Worker
{
73 let thread
= thread
::spawn(move || loop {
74 let job
= receiver
.lock().unwrap().recv().unwrap();
76 println
!("Worker {} got a job; executing.", id
);