Advertisement
Advanced Python, Decorators

How would you implement a thread-safe caching decorator that correctly handles concurrent calls from multiple threads?

Short answer

Protect the shared cache dictionary with a threading.Lock inside the decorator, ensuring only one thread can check-and-update the cache at a time — without this, two threads could simultaneously see a cache miss and both compute (and potentially double-write) the same expensive…

Save Python mock interview
Advertisement
AModel answer
Protect the shared cache dictionary with a threading.Lock inside the decorator, ensuring only one thread can check-and-update the cache at a time — without this, two threads could simultaneously see a cache miss and both compute (and potentially double-write) the same expensive result, or corrupt the dict during concurrent modification.
import threading, functools

def thread_safe_cache(func):
    cache = {}
    lock = threading.Lock()
    @functools.wraps(func)
    def wrapper(*args):
        with lock:
            if args not in cache:
                cache[args] = func(*args)
            return cache[args]
    return wrapper
Real-world example
Building a thread-safe memoization decorator for a function called concurrently from multiple worker threads in a web server.
Likely follow-ups
  • Does functools.lru_cache already provide this same thread-safety guarantee internally, or would you still need to add your own locking?
Related topics