Created
December 22, 2018 09:41
-
-
Save mitnk/881ad1b8f58543dd76c007cac3f375a9 to your computer and use it in GitHub Desktop.
Lifetime with Thread (Mutex, Arc) in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Thanks: https://stackoverflow.com/a/53894298/665869 | |
use std::collections::HashMap; | |
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
type Map = HashMap<String, String>; | |
fn handle_n_times(count: i32, arc_map: Arc<Mutex<Map>>) { | |
for i in 0..count { | |
let clone_arc = arc_map.clone(); | |
thread::spawn(move || { | |
let mut map = clone_arc.lock().unwrap(); | |
map.insert(format!("key-{}", i), format!("value-{}", i)); | |
}); | |
} | |
} | |
fn print_map_items(arc_map: Arc<Mutex<Map>>) { | |
let clone_arc = arc_map.clone(); | |
let map = clone_arc.lock().unwrap(); | |
for (k, v) in map.iter() { | |
println!("k: {} v: {}", k, v); | |
} | |
} | |
fn main() { | |
let arc_map = Arc::new(Mutex::new(Map::new())); | |
handle_n_times(5, arc_map.clone()); | |
// todo: join the threads above, wait them till finished | |
print_map_items(arc_map.clone()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment