目前,我正在阅读 Rust 书的最后一章,实现 HTTP 服务器的正常关闭。
现在我想稍微扩展一下逻辑,并在按 Ctrl-c 后触发正常关闭。因此我使用ctrlc crate。
但由于各种借用检查器错误,我无法使其工作:
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
ctrlc::set_handler(|| {
// dropping will trigger ThreadPool::drop and gracefully shutdown the running workers
drop(pool); // compile error, variable is moved here
})
.unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了使用Arc<>和附加mpsc 通道的多种方法,但没有成功。
为了使其发挥作用,最佳实践是什么?