I am trying to write to a HashMap using the Arc<Mutex<T>> pattern as part of a website scraping exercise inspired from the Rust cookbook.
This first part uses tokio runtime. I cannot get past the tasks being completed and returning the HashMap as it just hangs.
type Db = Arc<Mutex<HashMap<String, bool>>>; pub async fn handle_async_tasks(db: Db) -> BoxResult<HashMap<String, bool>> { let links = NodeUrl::new("https://www.inverness-courier.co.uk/") .await .unwrap(); let arc = db.clone(); let mut handles = Vec::new(); for link in links.links_with_paths { let x = arc.clone(); handles.push(tokio::spawn(async move { process(x, link).await; })); } // for handle in handles { // handle.await.expect("Task panicked!"); // } < I tried this as well> futures::future::join_all(handles).await; let readables = arc.lock().await; for (key, value) in readables.clone().into_iter() { println!("Checking db: k, v ==>{} / {}", key, value); } let clone_db = readables.clone(); return Ok(clone_db); } async fn process(db: Db, url: Url) { let mut db = db.lock().await; println!("checking {}", url); if check_link(&url).await.is_ok() { db.insert(url.to_string(), true); } else { db.insert(url.to_string(), false); } } async fn check_link(url: &Url) -> BoxResult<bool> { let res = reqwest::get(url.as_ref()).await?; Ok(res.status() != StatusCode::NOT_FOUND) } pub struct NodeUrl { domain: String, pub links_with_paths: Vec<Url>, } #[tokio::main] async fn main() { let db: Db = Arc::new(Mutex::new(HashMap::new())); let db = futures::executor::block_on(task::handle_async_tasks(db)); } I would like to return the HashMap to main() where the main thread is blocked. How can I wait for all async threaded processes to be complete and return the HashMap?
main()function? Otherwise no one can tell you how to use thatHashMapin thereasyncstuff without any prior Rust experience.main()function. @sebpuetzNodeUrl?