Skip to content Skip to sidebar Skip to footer

How To Share A Cache Between Multiple Processes?

I'm using a LRU cache to speed up some rather heavy duty processing. It works well and speeds things up considerably. However... When I multiprocess, each process creates it's own

Solution 1:

I believe you can use a Manager to share a dict between processes. That should in theory let you use the same cache for all functions.

However, I think a saner logic would be to have one process that responds to queries by looking them up in the cache, and if they are not present then delegating the work to a subprocess, and caching the result before returning it. You could easily do that with

with concurrent.futures.ProcessPoolExecutor() as e:
    @functools.lru_cachedefwork(*args, **kwargs):
        return e.submit(slow_work, *args, **kwargs)

Note that work will return Future objects, which the consumer will have to wait on. The lru_cache will cache the future objects so they will be returned automatically; I believe you can access their data more than once but can't test it right now.

If you're not using Python 3, you'll have to install backported versions of concurrent.futures and functools.lru_cache.

Solution 2:

Pass the shared cache to each process. The parent process can instantiate a single cache and refer it to each process as an argument...

@utils.lru_cache(maxsize=300)defget_stuff(key):
    """This is the routine that does the stuff which can be cached.
    """return Stuff(key)

defprocess(stuff_obj):
    """This is the routine which multiple processes call to do work with that Stuff
    """# get_stuff(key) <-- Wrong; I was calling the cache from here
    stuff_obj.execute()

defiterate_stuff(keys):
    """This generates work for the processses.
    """for key in keys:
        yield get_stuff(key)  # <-- I can call the cache from the parentdefmain():
    ...
    keys = get_list_of_keys()
    for result in pool.imap(process, iterate_stuff(keys)):
         evaluate(result)
    ...

This example is simple because I can look up the cache before calling the process. Some scenarios might prefer to pass a pointer to the cache rather than the value. eg:

yield (key, get_stuff)

Katriel's put me on the right track and I would implement that answer, but, silly me, my mistake was even simpler to solve than what he suggested.

Post a Comment for "How To Share A Cache Between Multiple Processes?"