我正在尝试在 Actix-Web 框架中使用Arc
和实现共享状态Mutex
。下面的代码可以编译,但是当我运行它时,计数器有时会一直回到 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();
}