Skip to content

Commit 1f1dea3

Browse files
author
chaoyuepan
committed
add collections example
1 parent 210776b commit 1f1dea3

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

collections/src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use std::{sync::{Arc, Mutex}, collections::HashMap};
2+
3+
4+
pub fn common_thread_safe_collections() {
5+
let map: HashMap<i32, i32> = HashMap::new();
6+
let m = Arc::new(Mutex::new(map));
7+
8+
let mut handles = vec![];
9+
for i in 0..10 {
10+
let m = Arc::clone(&m);
11+
handles.push(std::thread::spawn(move || {
12+
let mut map = m.lock().unwrap();
13+
map.insert(i, i);
14+
}));
15+
}
16+
17+
for handle in handles {
18+
handle.join().unwrap();
19+
}
20+
21+
println!("HashMap: {:?}", *m.lock().unwrap());
22+
}

collections/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use collections;
1+
use collections::*;
22

33
fn main() {
4-
println!("Hello, world!");
4+
common_thread_safe_collections();
55
}

0 commit comments

Comments
 (0)