]> git.proxmox.com Git - rustc.git/blame - src/doc/book/listings/ch20-web-server/listing-20-19/src/lib.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / listings / ch20-web-server / listing-20-19 / src / lib.rs
CommitLineData
923072b8
FG
1use std::{
2 sync::{mpsc, Arc, Mutex},
3 thread,
4};
74b04a01
XL
5
6pub struct ThreadPool {
7 workers: Vec<Worker>,
8 sender: mpsc::Sender<Job>,
9}
10
11// ANCHOR: here
12// --snip--
13
14type Job = Box<dyn FnOnce() + Send + 'static>;
15
16impl ThreadPool {
17 // --snip--
18 // ANCHOR_END: here
19 /// Create a new ThreadPool.
20 ///
21 /// The size is the number of threads in the pool.
22 ///
23 /// # Panics
24 ///
25 /// The `new` function will panic if the size is zero.
26 pub fn new(size: usize) -> ThreadPool {
27 assert!(size > 0);
28
29 let (sender, receiver) = mpsc::channel();
30
31 let receiver = Arc::new(Mutex::new(receiver));
32
33 let mut workers = Vec::with_capacity(size);
34
35 for id in 0..size {
36 workers.push(Worker::new(id, Arc::clone(&receiver)));
37 }
38
39 ThreadPool { workers, sender }
40 }
41 // ANCHOR: here
42
43 pub fn execute<F>(&self, f: F)
44 where
45 F: FnOnce() + Send + 'static,
46 {
47 let job = Box::new(f);
48
49 self.sender.send(job).unwrap();
50 }
51}
52
53// --snip--
54// ANCHOR_END: here
55
56struct Worker {
57 id: usize,
58 thread: thread::JoinHandle<()>,
59}
60
61impl Worker {
62 fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
63 let thread = thread::spawn(|| {
64 receiver;
65 });
66
67 Worker { id, thread }
68 }
69}