我正在尝试使用Arc和Mutex在Actix-Web框架中实现共享状态。下面的代码可以编译,但当我运行它时,计数器有时会一直返回到0。我如何防止这种情况发生?
use actix_web::{web, App, HttpServer};
use std::sync::{Arc, Mutex};
// This struct represents state
struct AppState {
app_name: String,
counter: Arc<Mutex<i64>>,
}
fn index(data: web::Data<AppState>) -> String {
let mut counter = data.counter.lock().unwrap();
*counter += 1;
format!("{}", counter)
}
pub fn main() {
HttpServer::new(|| {
App::new()
.hostname("hello world")
.register_data(web::Data::new(AppState {
app_name: String::from("Actix-web"),
counter: Arc::new(Mutex::new(0)),
}))
.route("/", web::get().to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}发布于 2019-12-30 00:25:55
HttpServer::new接受一个闭包,每个运行服务器的线程都会调用这个闭包。这意味着将创建多个AppState实例,每个线程一个实例。根据响应HTTP请求的线程的不同,您将获得不同的data实例,并因此获得不同的计数器值。
要防止这种情况发生,请在闭包外部创建web::Data<AppState>,并在HttpServer::new闭包内使用克隆的引用。
https://stackoverflow.com/questions/59276996
复制相似问题