Last active
April 29, 2020 17:36
-
-
Save samueleresca/1d661d15acbf1aab48b8943ff6acfc79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LRUCacheReaderWriterLock<T> | |
{ | |
private readonly Dictionary<int, LRUCacheItem<T>> _records =new Dictionary<int, LRUCacheItem<T>>(); | |
private readonly LinkedList<int> _freq = new LinkedList<int>(); | |
private readonly ReaderWriterLockSlim _rw = new ReaderWriterLockSlim(); | |
private readonly int _capacity; | |
public LRUCacheReaderWriterLock(int capacity) | |
{ | |
_capacity = capacity; | |
} | |
public int Capacity => _capacity; | |
public object Get(int key) | |
{ | |
_rw.EnterReadLock(); | |
var keyNotExists = !_records.ContainsKey(key); | |
if (keyNotExists) return null; | |
_rw.ExitReadLock(); | |
_rw.EnterWriteLock(); | |
_freq.Remove(key); | |
_freq.AddLast(key); | |
_rw.ExitWriteLock(); | |
try | |
{ | |
_rw.EnterReadLock(); | |
return _records[key].CacheValue; | |
} | |
finally | |
{ | |
_rw.ExitReadLock(); | |
} | |
} | |
public void Set(int key, T val) | |
{ | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment