File size: 1,393 Bytes
f31fe4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | # coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import threading
class RWLock(object):
def __init__(self):
self.__monitor = threading.Lock()
self.__exclude = threading.Lock()
self.readers = 0
def r_lock(self):
with self.__monitor:
self.readers += 1
if self.readers == 1:
self.__exclude.acquire()
def r_un_lock(self):
with self.__monitor:
self.readers -= 1
if self.readers == 0:
self.__exclude.release()
def lock(self):
self.__exclude.acquire()
def un_lock(self):
self.__exclude.release()
class Cache(object):
def __init__(self):
self._cache = {}
self.lock = RWLock()
def put(self, key, value):
try:
self.lock.lock()
self._cache[key] = value
finally:
self.lock.un_lock()
def get(self, key):
try:
self.lock.r_lock()
if key in self._cache:
return self._cache[key]
else:
return None
finally:
self.lock.r_un_lock()
def has_key(self, key):
if key in self._cache:
return True
else:
return False
|