I am trying to add lock to timed key value store with python. Following is my code:
class TimedKVWithLock:
def __init__(self):
self.data = {}
self._locks = defaultdict(threading.Lock)
def put(self, key, value):
with self._locks[key]:
timestamp = int(time.time())
if key not in self.data:
self.data[key] = []
self.data[key].append([timestamp, value])
def get(self, key, timestamp):
if key not in self.data:
return ""
with self._locks[key]:
val_list = self.data[key]
l = 0
r = len(val_list) - 1
result = ""
while l <= r:
m = (l + r) // 2
if val_list[m][0] <= timestamp:
result = val_list[m][1]
l = m + 1
else:
r = m - 1
return result
Have some quick questions:
-
Is following code going to work for multi threads case? Say I have N threads assessing the key values
-
Do I need a global lock on self.data when I check if key exists in self.data?
thanks!