Why application state is always wrapped in an Arc pointer? #2760
-
|
The documentation introduces us about the application state, and how we can (a) share it between worker threads or (b) not. a. To share state between worker threads we create the #[actix_web::main]
async fn main() -> std::io::Result<()> {
// Note: web::Data created outside the closure
let state = web::Data::new("some state");
HttpServer::new(move || {
// move state into the closure
App::new()
.app_data(state.clone()) // <- register the created data
.default_service(web::to(handler))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}This way, all worker threads share the same single b. If we don't want to share state between worker threads, so each worker thread has its own instance of #[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.app_data(web::Data::new("some state")) // <- Note: web::Data created inside the closure
.default_service(web::to(handler))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}This way, each worker thread has a distinct Question: is it necessary the use of an |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
The most common use case for Alternatives for b):
|
Beta Was this translation helpful? Give feedback.
-
|
a. No you don't share anything that you move in to the HttpServer::new() closure. Everything inside is thread local and are not moved between threads unless you explicit call it from middleware or handler function. You get a sense of sharing state because of the Arc smart pointer where multiple instances of Arc can be used to deref to the inner T. b. This is the same thing as point a but it's more obvious since you are already inside the closure. answer to your question:
|
Beta Was this translation helpful? Give feedback.
The most common use case for
Datais to create shared state which is why it works this way; it is a safe default.Alternatives for b):
LocalDatafrom actix-web-labRcinternally.app_data("some state")+req.app_data::<&'static str>()whereasync fn handler(req: HttpRequest) { ...