It’s the same thing as this question but with actix.
I have multiple threads that read often, while another thread writes once a day. Don’t really care whether readers get an old copy of the data or a new one, as long as the memory gets updated
use serde::Serialize;
use actix_web::{HttpServer, Responder, get, App, HttpResponse, web};
#[derive(Serialize)]
struct MyStruct {
a: String,
b: Vec<String>,
}
#[get("get")]
async fn get(data: web::Data<MyStruct>) -> impl Responder {
return HttpResponse::Ok().json(data);
}
//not an actual route
#[get("set")]
async fn set(data: web::Data<MyStruct>) -> impl Responder {
//set data to some value
//
return HttpResponse::Ok();
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let data = web::Data::new(MyStruct::default());
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.service(get)
.service(set)
}).bind(("0.0.0.0", 8080))?
.run()
.await
}
>Solution :
I’m assuming that your reasoning for not wanting to use a Mutex is because that will not allow multiple threads to read the value at the same time, which would effective make that route have the performance of a single threaded route.
To allow multiple readers at a time but only one editor at a time you can use a RwLock. This will still make your threads unable to read while one thread is updating the data, but since that only happens once a day I think that’s probably acceptable.
(You also really don’t want to allow reading while the data is changing since you could get all sorts of weird partially updated or corrupt data, especially for more complex data structures).