From d36399b9583563b5ea6c0993f5760253af4ebea9 Mon Sep 17 00:00:00 2001 From: Chelsea Troy Date: Mon, 16 Dec 2019 15:59:29 -0600 Subject: [PATCH] Lock mutations of each type to the data and the log to prevent simultaneous commands on different threads from corrupting the data --- key_value_operations.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/key_value_operations.py b/key_value_operations.py index c668820..38a9314 100644 --- a/key_value_operations.py +++ b/key_value_operations.py @@ -1,4 +1,8 @@ +import threading + class KeyValueStore: + client_lock = threading.Lock() + def __init__(self): self.data = {} @@ -17,19 +21,20 @@ def execute(self, string_operation): response = "Sorry, I don't understand that command." - if operands[command] == "get": - response = self.get(operands[key]) - elif operands[command] == "set": - value = " ".join(operands[2:]) - self.set(operands[key], value) - response = f"key {operands[key]} set to {value}" - elif operands[command] == "delete": - self.delete(operands[key]) - response = f"key {key} deleted" - elif operands[command] == "show": - response = str(self.data) - else: - pass + with self.client_lock: + if operands[command] == "get": + response = self.get(operands[key]) + elif operands[command] == "set": + value = " ".join(operands[2:]) + self.set(operands[key], value) + response = f"key {operands[key]} set to {value}" + elif operands[command] == "delete": + self.delete(operands[key]) + response = f"key {key} deleted" + elif operands[command] == "show": + response = str(self.data) + else: + pass return response \ No newline at end of file