Sub topic 15
Making the Cache Safe for Multiple Threads
This chapter assumes you have the finished LRUCache from the earlier chapters and know Python's threading module at a basic level. You will add a lock so several threads can share one cache.
Why the cache is not thread-safe
A thread is a separate path of execution inside one program. Threads share memory, so two of them can touch the same cache at once. Python may switch between threads between any two bytecode instructions.
Both get and put change several things in more than one step:
getcallsmove_to_front, which runsremoveand thenadd_front. Between those calls the node is in neither position.putcheckslen(self.map), pops the oldest node, deletes its key, and then inserts the new one.
Suppose thread A has removed a node and thread B walks the list before A calls add_front. B can see broken prev and next links. Two threads can also both see a full cache and both evict, which removes an extra entry. The map and the list then disagree, and the errors show up later and unpredictably.
Note that get is not read-only. It reorders the list, so it needs the same protection as put.
Guarding with one lock
A lock lets only one thread at a time run a protected block. The simplest fix is to wrap the existing cache and acquire one lock around every public method.
import threading
class ThreadSafeLRUCache:
def __init__(self, capacity):
self._cache = LRUCache(capacity)
self._lock = threading.Lock()
def get(self, key):
with self._lock:
return self._cache.get(key)
def put(self, key, value):
with self._lock:
self._cache.put(key, value)The with statement releases the lock even if the body raises an exception. Keeping the wrapper separate means the single-threaded LRUCache stays simple and easy to test.
Trying it
This script starts eight threads that each insert and read 1,000 keys. With the lock in place, it finishes with a consistent cache.
def worker(cache, offset):
for i in range(1000):
cache.put(offset + i, i)
cache.get(offset + i)
cache = ThreadSafeLRUCache(100)
threads = [
threading.Thread(target=worker, args=(cache, n * 1000))
for n in range(8)
]
for t in threads:
t.start()
for t in threads:
t.join()
print(len(cache._cache.map)) # 100Limits of this approach
- One lock serializes everything. Threads wait for each other even when they use different keys. Python's global interpreter lock already limits parallel execution of Python code, so this cost is usually acceptable.
- Calls are atomic one at a time. A sequence such as
getfollowed byputis not atomic. Another thread can change the cache between the two calls. If you need "get or compute and store", add a method that holds the lock for the whole sequence. - Do not call locked methods from inside locked methods. A plain
Lockblocks forever if the same thread tries to acquire it twice. Usethreading.RLockif you add methods that call each other.
Exercise
Why can two threads calling put on a full cache without a lock leave the cache over capacity or inconsistent?
Show answer
Both threads can check len(self.map) before either has changed it, so both see the same state and then run the evict-and-insert steps. The map and the linked list are updated in several separate steps, so the interleaved updates can leave them disagreeing, or skip an eviction. A single lock around each public method makes each put run as one unit.