6 pub struct ThreadPool
{
8 sender
: mpsc
::Sender
<Job
>,
14 type Job
= Box
<dyn FnOnce() + Send
+ '
static>;
19 /// Create a new ThreadPool.
21 /// The size is the number of threads in the pool.
25 /// The `new` function will panic if the size is zero.
26 pub fn new(size
: usize) -> ThreadPool
{
29 let (sender
, receiver
) = mpsc
::channel();
31 let receiver
= Arc
::new(Mutex
::new(receiver
));
33 let mut workers
= Vec
::with_capacity(size
);
36 workers
.push(Worker
::new(id
, Arc
::clone(&receiver
)));
39 ThreadPool { workers, sender }
43 pub fn execute
<F
>(&self, f
: F
)
45 F
: FnOnce() + Send
+ '
static,
47 let job
= Box
::new(f
);
49 self.sender
.send(job
).unwrap();
58 thread
: thread
::JoinHandle
<()>,
62 fn new(id
: usize, receiver
: Arc
<Mutex
<mpsc
::Receiver
<Job
>>>) -> Worker
{
63 let thread
= thread
::spawn(|| {