Not sure if it's appropriate to ask crate-specific questions here, but I have a question about Tokio.
I want to learn how threads can modify data structures created in the main thread.
Here's a simple example that doesn't work because it says dog_map
does not live long enough.
I imagine there is an easy fix that I'm not seeing.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type DogMap = Arc<Mutex<HashMap<String, String>>>; // name to breed
async fn add_nelson_dogs(dog_map: &DogMap) {
let mut map = dog_map.lock().unwrap();
map.insert("Maisey".to_string(), "Treeing Walker Coonhound".to_string());
map.insert(
"Oscar".to_string(),
"German Shorthaired Pointer".to_string(),
);
// Do I need to explicitly unlock here?
}
async fn add_volkmann_dogs(dog_map: &DogMap) {
let mut map = dog_map.lock().unwrap();
map.insert("Comet".to_string(), "Whippet".to_string());
// Do I need to explicitly unlock here?
}
#[tokio::main]
async fn main() {
let map: HashMap<String, String> = HashMap::new();
let wrapped_map = Arc::new(Mutex::new(map));
tokio::spawn(add_nelson_dogs(&wrapped_map)).await;
tokio::spawn(add_volkmann_dogs(&wrapped_map)).await;
let map = wrapped_map.lock().unwrap();
println!("{:?}", map);
}