I'm trying to implement shared state in the Actix-Web framework with Arc
and Mutex
. The following code compiles, but when I run it, the counter sometimes goes all the way back to 0. How do I prevent that from happening?
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();
}