Skip to content

Instantly share code, notes, and snippets.

@highway900
Last active July 16, 2020 09:07
Show Gist options
  • Save highway900/41d1cbaadf9a7f18b0c0fce2895bd2d1 to your computer and use it in GitHub Desktop.
Save highway900/41d1cbaadf9a7f18b0c0fce2895bd2d1 to your computer and use it in GitHub Desktop.
Shared state across multiple servers
use std::sync::{RwLock};
use futures::future;
use actix_web::{web, App, HttpServer};
struct AppStateWithCounter {
counter: RwLock<i32>,
}
async fn write(data: web::Data<AppStateWithCounter>) -> String {
let mut counter = data.counter.write().unwrap();
*counter += 1;
format!("Request number: {}", counter) // <- response with count
}
async fn read(data: web::Data<AppStateWithCounter>) -> String {
let counter = data.counter.read().unwrap();
format!("Request number: {}", counter) // <- response with count
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
let counter = web::Data::new(AppStateWithCounter {
counter: RwLock::new(0),
});
let s1 = HttpServer::new(move || {
// move counter into the closure
App::new()
.app_data(counter.clone())
.route("/", web::get().to(write))
})
.bind("127.0.0.1:8000")?
.run();
let s2 = HttpServer::new(move || {
App::new()
.app_data(counter.clone())
.route("/", web::get().to(read))
})
.bind("127.0.0.1:9000")?
.run();
future::try_join(s1, s2).await;
Ok(())
}
use std::thread;
use std::sync::Arc;
use std::sync::Mutex;
fn main() {
let answer = Arc::new(Mutex::new(42));
let mut threads = vec![];
for i in 0..5 {
let answer_ref = answer.clone();
let t = thread::spawn(move || {
let mut answer = answer_ref.lock().unwrap();
*answer = 55;
println!("{}: {}", i, answer);
});
threads.push(t);
}
for t in threads {
t.join().unwrap();
}
let ar = answer.lock().unwrap();
assert_eq!(*ar, 55);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment