Skip to content

Instantly share code, notes, and snippets.

@joshkunz
Created February 20, 2013 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshkunz/4998910 to your computer and use it in GitHub Desktop.
Save joshkunz/4998910 to your computer and use it in GitHub Desktop.
The locking section of some caching code I wrote.
@classmethod
def resolve(cls, request, caching_client):
"""If this request isn't yet cached, cache it, otherwise return
a file containing the cached contents"""
hash = cls.hash(request)
is_caching = False
active_thread = None
# If there is no cached file
if not cls.hit(hash):
# obtain a lock for the active caches
with cls.active_lock:
# if there is no active cache make one
if hash not in cls.active_caches:
print "Cache Miss:", urlunparse(request.url)
active_thread = Cacher(cls.new_cache(hash), request, caching_client)
is_caching = True
active_thread.daemon = True
active_thread.start()
cls.active_caches[hash] = active_thread
# otherwise get th already active cache
else:
print "Cache Loading:", urlunparse(request.url)
active_thread = cls.active_caches[hash]
else:
print "Cache Hit:", urlunparse(request.url)
# If our request if being actively cached, wait for it to complete
if active_thread is not None:
active_thread.join()
# If our request was cached by the Cacher, return None, the file
# was already sent to the server (this is a speed improvement
if is_caching:
return None
return cls.cache_lookup(hash)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment