Kistaro

Reader/writer lazy cache fill algorithm

Feb 12th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. with cache_lock.reader_lock:
  2.     x = cache_fetch_under_rlock(params)
  3.     if x is not None:
  4.         return x
  5.  
  6. # cache miss; must populate
  7. with cache_lock.writer_lock:
  8.     x = cache_fetch_under_rlock(params)
  9.     if x is not None:
  10.         # oops, we didn't need to write, oh well
  11.         return x
  12.     x = do_the_expensive_thing(params)
  13.     cache_write_under_wlock(params, x)
  14.     return x
  15.    
  16. # do_the_expensive_thing may repeat this pattern with a different lock,
  17. # if it has its own cache or pipelined single source of truth. This
  18. # is a nestable, generic pattern for maximizing cache throughput
  19. # while provably not duplicating the expensive thing. It has the
  20. # disadvantage of holding the cache lock for the entire Expensive Thing
  21. # but this is often appropriate; if it is worse to unnecessarily hold
  22. # the writer lock than it is to duplicate work, however...
  23.  
  24. with cache_lock.reader_lock:
  25.     x = cache_fetch_under_rlock(params)
  26.     if x is not None:
  27.         return x
  28.  
  29. z = do_the_expensive_thing(params)
  30.  
  31. with cache_lock.writer_lock:
  32.     x = cache_fetch_under_rlock(params)
  33.     if x is not None:
  34.         # oops
  35.         return x  # it is more GC-memory-efficient to throw z away;
  36.                   # under garbage collection, prefer old objects
  37.     cache_write_under_wlock(params, z)
  38.     return z
Advertisement
Add Comment
Please, Sign In to add comment