1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
use std::cell::RefCell; use std::collections::HashMap; use std::sync::{Arc, RwLock}; #[macro_use] extern crate lazy_static; lazy_static! { pub static ref GIDMap: Arc<RwLock<IDMap>> = Arc::new(RwLock::new(IDMap::new())); } pub struct IDMap(HashMap<String, u64>); impl IDMap { pub fn new() -> IDMap { IDMap(HashMap::new()) } pub fn current(&mut self, key: &str) -> u64 { if let Some(x) = self.0.get_mut(key) { *x } else { let v = 0; self.0.insert(key.to_string(), v); v } } pub fn next(&mut self, key: &str) -> u64 { let next = self.current(key) + 1; self.0.insert(key.to_string(), next); next } } #[cfg(test)] mod tests { #[test] fn it_works() { use super::GIDMap; use std::thread; let r1 = GIDMap.clone(); let r2 = GIDMap.clone(); let r3 = GIDMap.clone(); let r4 = GIDMap.clone(); let r5 = GIDMap.clone(); let th1 = thread::spawn(move || { println!("{}", r1.write().unwrap().current("hello")); }); let th2 = thread::spawn(move || { println!("{}", r2.write().unwrap().current("hello")); }); th1.join(); th2.join(); let th3 = thread::spawn(move || { println!("{}", r3.write().unwrap().next("hello")); }); let th4 = thread::spawn(move || { println!("{}", r4.write().unwrap().next("hello")); }); let th5 = thread::spawn(move || { println!("{}", r5.write().unwrap().current("hello")); }); th3.join(); th4.join(); th5.join(); } }