-
Rust연습❤️HashMap, Arc, Mutex, thread연습코딩Coding/Rust연습 2022. 8. 13. 18:51728x90
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반응형'코딩Coding > Rust연습' 카테고리의 다른 글
Rust Machine learning code 불완전함 (0) 2022.08.13 러스트연습❤️ 뭔가 제자리에서 출력되는거 (0) 2022.08.13 Rust연습❤️“rust spinning rod animation in text” Code Answer (0) 2022.08.13 Rust연습❤️Processing 0~100%올라가는 프린트 ㅎㅎ (0) 2022.08.13 Rust연습❤️] Hello from asm__assembly코드 연습 (0) 2022.07.03 Rust연습❤️] Displaying raw pointers (0) 2022.07.03 Rust연습❤️내 컴퓨터에 병렬 실행 가능한 코어수 알아보기available_parallelism (0) 2022.06.29 Rust – Fibonacci using Recursion and Iteration (0) 2022.06.26