我读过这个将我们的单线程服务器变成多线程服务器 https://doc.rust-lang.org/book/ch20-02-multithreaded.html。
并试图去实施它。
我写了这个:
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
type task = dyn FnOnce() + Send + 'static;
pub struct Threadpool {
threads: Vec<thread::JoinHandle<()>>,
rx: Arc<Mutex<Receiver<Box<task>>>>,
tx: Sender<Box<task>>,
}
impl Threadpool {
pub fn new(size: usize) -> Threadpool {
let mut tasks = Vec::with_capacity(size);
let (tx, rx): (Sender<Box<task>>, Receiver<Box<task>>) = channel();
let rx = Arc::new(Mutex::new(rx));
for _ in 0..size {
let rx = rx.clone();
let task = thread::spawn(move || {
loop {
let job= rx.lock().unwrap().recv().unwrap();
job();
}
});
tasks.push(task);
}
Threadpool {
threads: tasks,
rx,
tx,
}
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
self.tx.send(Box::new(f)).unwrap();
}
}
有用。
但当我改变时
let job= rx.lock().unwrap().recv().unwrap();
job();
to
rx.lock().unwrap().recv().unwrap()();
当我打开时localhost:port/sleep
,然后打开localhost:port
,需要 5 秒。
我在 main 中设置了这个
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
我已经知道了while let
会导致这种情况。
但我不明白为什么我上面的代码也会导致这种情况。
有谁能给我答案吗。