From c6f092fc809b70febf38e3ce7ace463aa1f370b7 Mon Sep 17 00:00:00 2001 From: Jan Niehusmann Date: Sun, 14 Oct 2018 19:56:25 +0200 Subject: [PATCH] Encapsulate app state in Arc> (#54) --- state/src/main.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/state/src/main.rs b/state/src/main.rs index 3552b433..2f0852d0 100644 --- a/state/src/main.rs +++ b/state/src/main.rs @@ -15,21 +15,22 @@ extern crate actix; extern crate actix_web; extern crate env_logger; -use std::cell::Cell; +use std::sync::Arc; +use std::sync::Mutex; use actix_web::{middleware, server, App, HttpRequest, HttpResponse}; /// Application state struct AppState { - counter: Cell, + counter: Arc>, } /// simple handle fn index(req: &HttpRequest) -> HttpResponse { println!("{:?}", req); - req.state().counter.set(req.state().counter.get() + 1); + *(req.state().counter.lock().unwrap()) += 1; - HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.get())) + HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.lock().unwrap())) } fn main() { @@ -38,7 +39,7 @@ fn main() { let sys = actix::System::new("ws-example"); server::new(|| { - App::with_state(AppState{counter: Cell::new(0)}) // <- create app with state + App::with_state(AppState{counter: Arc::new(Mutex::new(0))}) // <- create app with state // enable logger .middleware(middleware::Logger::default()) // register simple handler, handle all methods