我的应用程序是根据各地使用Actix的和Actix的-网库(库-A)。我加入了一个运行HTTP服务器,也使用Actix的的web第二个库(库-B)。我用这一个单独的线程和actix::system
。在SIGINT,只有图书馆-B Actix的系统关闭,离开图书馆-A的运行。没有后续SIGINT关闭正在运行的Actix的系统。
什么是正确的方式来方便地关闭两个运行中Actix的系统?
图书馆-B的代码,开始一个新的Actix的系统并运行一个HTTP服务器:
thread::spawn(move || {
let sys = actix::System::new("monitor");
server::new(|| App::new()
.route("/metrics", http::Method::GET, endpoint))
.bind(format!("0.0.0.0:{}", port))
.unwrap()
.start();
sys.run();
println!("Closing monitor actix system");
// --- SIGINT gets me here... how do I shut down gracefully?
});
它是正确的,我开始一个新的系统,一个独立的库?如何正常关闭?
你能赶上与Ctrl+C
箱的使用ctrlc信号。
在主线程的使用可以在Rust-Lang-Nursery找到
既然你从你的主线程和后创建线程你在主线程擦肩而过信号,那么你可以通过看这些线程共享布尔值,正常关闭其他线程。
作为一个另外有一种stop功能,这是特定于Actix的。
您还可以使用瓒信号箱和写这样回答here您的自定义实现
要创建自己的关断逻辑
检查所有线程共享的弧原子布尔值,当该变量在主线程改变停止执行。既然你捉对主线程ctrl-c
信号也可以通知其他演员像线程以下:
use ctrlc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let running = Arc::new(AtomicBool::new(true));
let running2 = running.clone();
let r = running.clone();
let thandle = thread::spawn(move || {
while running2.load(Ordering::Relaxed) {
//Do your logic here
}
println!("Thread1 stopped.")
});
let thandle2 = thread::spawn(move || {
while running.load(Ordering::Relaxed) {
//Do your different logic here
}
println!("Thread2 stopped.")
});
ctrlc::set_handler(move || {
r.store(false, Ordering::Relaxed);
})
.expect("Error setting Ctrl-C handler");
println!("Waiting for Ctrl-C...");
let _ = thandle.join();
let _ = thandle2.join();
}