Execute the whole request in a thread

This commit is contained in:
p11 2023-09-16 17:27:30 +02:00
parent 34b8307426
commit 64e0637349

View File

@ -28,7 +28,7 @@ fn main() {
return; return;
}; };
let mut context = Context::default(); let context: Arc<Mutex<Context>> = Arc::default();
let mut pool = ThreadPool::new(4); let mut pool = ThreadPool::new(4);
let mut args = env::args(); let mut args = env::args();
@ -52,7 +52,9 @@ fn main() {
} }
} }
handle_connection(&mut context, &path, stream, &pool); let context = context.clone();
let path = path.clone();
pool.execute(move || handle_connection(context, path, stream));
} }
} }
@ -133,7 +135,7 @@ struct Context {
infos: HashMap<Box<str>, Arc<Mutex<SiteInfo>>>, infos: HashMap<Box<str>, Arc<Mutex<SiteInfo>>>,
} }
fn handle_connection(context: &mut Context, path: &Path, mut stream: TcpStream, pool: &ThreadPool) { fn handle_connection(context: Arc<Mutex<Context>>, path: PathBuf, mut stream: TcpStream) {
let Some(request) = Request::from(&stream) else { let Some(request) = Request::from(&stream) else {
eprintln!("Invalid request!"); eprintln!("Invalid request!");
return; return;
@ -193,7 +195,7 @@ fn handle_connection(context: &mut Context, path: &Path, mut stream: TcpStream,
if relative_path.split('/').any(|name| name == "Images") { if relative_path.split('/').any(|name| name == "Images") {
let path = path.to_path_buf(); let path = path.to_path_buf();
pool.execute(move || reply_image(stream, &relative_path, path)); reply_image(stream, &relative_path, path);
return; return;
} }
@ -209,8 +211,9 @@ fn handle_connection(context: &mut Context, path: &Path, mut stream: TcpStream,
} }
} }
let info = if let Ok(mut context) = context.lock() {
use Entry::*; use Entry::*;
let info = match context.infos.entry(relative_path.clone().into_boxed_str()) { match context.infos.entry(relative_path.clone().into_boxed_str()) {
Occupied(o) => o.get().clone(), Occupied(o) => o.get().clone(),
Vacant(v) => v Vacant(v) => v
.insert(Arc::new(Mutex::new( .insert(Arc::new(Mutex::new(
@ -221,10 +224,13 @@ fn handle_connection(context: &mut Context, path: &Path, mut stream: TcpStream,
.unwrap_or_default(), .unwrap_or_default(),
))) )))
.clone(), .clone(),
}
} else {
return;
}; };
let path = path.to_path_buf(); let path = path.to_path_buf();
pool.execute(move || {
handle_relative_connection( handle_relative_connection(
info, info,
stream, stream,
@ -236,7 +242,6 @@ fn handle_connection(context: &mut Context, path: &Path, mut stream: TcpStream,
&data_path, &data_path,
start_level, start_level,
) )
});
} }
fn reply_image(mut stream: TcpStream, relative_path: &str, mut path: PathBuf) { fn reply_image(mut stream: TcpStream, relative_path: &str, mut path: PathBuf) {