In order to learn rust and concurrency , im trying to share a common hashmap between actix web server and a parallel thread
- Theres one thread which updates a hashmap with the current timestamp every 10 seconds
- theres a GET API which returns the latest timestamp provided in the hashmap
heres my code
use actix_web::{web, App, HttpServer};
use std::collections::HashMap;
use chrono::prelude::*;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
async fn get_latest_timestamp(data: web::Data<Arc<Mutex<HashMap<String, String>>>>) -> String {
let wrapped_data = data.lock().unwrap();
match wrapped_data.get("time_now") {
Some(i) => String::from(i),
None => String::from("None")
}
}
fn update_timestamps(data: Arc<Mutex<HashMap<String, String>>>) -> () {
loop {
thread::sleep(Duration::from_secs(10));
println!("Updating time.... ");
let now: DateTime<Local> = Local::now();
let mut data = data.lock().unwrap();
data.insert(String::from("time_now"), now.to_rfc2822());
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let mut hash = HashMap::new();
hash.insert(String::from("time_now"), Local::now().to_rfc2822());
let data = Arc::new(Mutex::new(hash));
let hash_clone = Arc::clone(&data);
thread::spawn(move || {
update_timestamps(hash_clone)
});
HttpServer::new( move || {
App::new()
.data(data.clone())
.route("/", web::get().to(get_latest_timestamp))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
Is there anything i could do handle better. A couple of questions i do have
How does one generally handle errors that occur on the parallel thread? is the main thread notified in someway?
the code in
update_timestamps
runs in a continous loop - is there a better way to handle it so that it cleanly exits?