Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ class LRUEngineCache(DataKeyedCache):
one thread at a time reads or writes the cache, which lets requests
processed on several threads share it.
"""

# Held only while a cache makes its own lock, for a subclass whose
# constructor sets the cache without calling this constructor.
_making_lock = threading.Lock()

def __init__(self, size = 1000):
"""!
Constructor for LRUCache
Expand All @@ -43,12 +48,25 @@ def __init__(self, size = 1000):
self.cache = LRUCache(maxsize=size)
self._lock = threading.Lock()

def _get_lock(self):

# A subclass may not have called the constructor, so the lock is
# made on first use, once, however many threads ask at the same time.
lock = getattr(self, "_lock", None)
if lock is None:
with LRUEngineCache._making_lock:
lock = getattr(self, "_lock", None)
if lock is None:
lock = threading.Lock()
self._lock = lock
return lock

def get_cache_value (self, cache_key):

with self._lock:
with self._get_lock():
return self.cache.get(cache_key)

def set_cache_value(self, key, value):

with self._lock:
with self._get_lock():
self.cache[key] = value
30 changes: 30 additions & 0 deletions pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,35 @@ def work(number):
self.assertIsNone(cache.get_cache_value(0))


class OwnCacheEngineCache(LRUEngineCache):
"""A subclass that sets its cache itself and does not call the
constructor of LRUEngineCache."""

def __init__(self, cache):
self.cache = cache


class SubclassWithoutConstructorTests(unittest.TestCase):

def test_a_subclass_that_skips_the_constructor_reads_and_writes(self):
cache = OwnCacheEngineCache(LRUCache(maxsize=CACHE_SIZE))
cache.set_cache_value(1, value_of(1))
self.assertEqual(value_of(1), cache.get_cache_value(1))
self.assertIsNone(cache.get_cache_value(2))

def test_its_threads_share_one_lock_made_on_first_use(self):
recording = OverlapRecordingCache(CACHE_SIZE)
cache = OwnCacheEngineCache(recording)

def work(number):
for call in range(CALLS_PER_THREAD):
key = (number + call) % KEYS
cache.set_cache_value(key, value_of(key))
cache.get_cache_value(key)

self.assertEqual([], run_threads(work))
self.assertEqual(1, recording.most_inside)


if __name__ == "__main__":
unittest.main()
Loading