use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref GIDMap: Arc<RwLock<IDMap>> = Arc::new(RwLock::new(IDMap::new()));
}
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();
}
}