코딩Coding/Rust연습
Rust연습❤️HashMap, Arc, Mutex, thread연습
내인생PLUS
2022. 8. 13. 18:51
728x90
main.rs
// 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());
}
결과
cargo run
Compiling rust_polyglot v0.1.0 (/Users/globalyoung/Documents/Project/Github/rust_project/rust_polyglot)
Finished dev [unoptimized + debuginfo] target(s) in 2.27s
Running `target/debug/rust_polyglot`
k: key-2 v: value-2
k: key-0 v: value-0
k: key-1 v: value-1
https://gist.github.com/mitnk/881ad1b8f58543dd76c007cac3f375a9
https://stackoverflow.com/questions/53892938/rust-lifetime-issue-with-threads/53894298#53894298
반응형