【发布时间】:2023-02-07 09:13:23
【问题描述】:
我读过这个Turning Our Single-Threaded Server into a Multithreaded Server。 并试图实施它。
我写了这个:
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();
到
rx.lock().unwrap().recv().unwrap()();
当我打开localhost:port/sleep,再打开localhost:port时,需要5秒。
我在主要设置这个
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
我已经知道 while let 会导致这种情况。
但我不明白为什么我上面的代码也会导致这种情况。
谁能给我答案。
【问题讨论】:
-
我发现
if let Ok(job) = rx.lock().unwrap().recv(){ job(); }会导致与rx.lock().unwrap().recv().unwrap()();相同的事情
标签: rust threadpool mutex