jeromefroe / lru-rs

An implementation of a LRU cache
https://docs.rs/lru/
MIT License
642 stars 106 forks source link

Weird issue where get blocks when using an Arc<Mutex>> #110

Open volfco opened 3 years ago

volfco commented 3 years ago

I'm using a shared LRU cache in my crate, and I ran into this weird issue. I'm not sure if I'm stupid, Rust is stupid, or there is some error with the crate.

I would expect this code to either error out, panic, or work. But it just hangs.


let my_arc = Arc::new(Mutex::new(lru::LruCache::new(1024)));

let local_arc = my_arc.clone()

let data = local_arc.lock().unwrap().get("my_key".to_string());

My guess is that local_arc.lock().unwrap() is returning a non mutable reference, and Rust is not seeing that it should be and freaks out. Converting the above code to the following works:


let my_arc = Arc::new(Mutex::new(lru::LruCache::new(1024)));

let local_arc = my_arc.clone()

let mut handle = local_arc.lock().unwrap();
let data = handle.get("my_key".to_string());

I assume I should have done .get_mut() vs .lock() but I am still wondering if the lack of compiler freakout is the result of Rust being stupid, or something your crate is not doing. I looked at your code and it looks fine, so I'm not sure.

jeromefroe commented 3 years ago

Hi @volfco, thanks for the issue! I'm not sure either why the first example would just hang, that seems very odd! I think you're second example is the right approach to take though as I think in the first example the mutex handle that's returned by the lock method, and used to access the underlying cache, will go out of scope at the end of the line. In which case you won't be able to access data in any subsequent steps because the lifetime of the handle has ended.