tkem/cachetools

How to ensure thread safety in multithreading? example?

Closed this issue · 1 comments

@cached(cache=TTLCache(maxsize=10000, ttl=6000))
def get_ip_geo(ip: str):
      return "xxxxxx"
    

I have a function like that, reporting keyerror in multithreading.
How can I solve this problem?

tkem commented

https://cachetools.readthedocs.io/en/latest/#cachetools.cached

If lock is not None, it must specify an object implementing the context manager protocol. Any access to the cache will then be nested in a with lock: statement. This can be used for synchronizing thread access to the cache by providing a threading.Lock instance, for example.

There's even an example for this...