Skip to content
Snippets Groups Projects
Commit 206ff405 authored by Mengqi Chen's avatar Mengqi Chen
Browse files

add lockmanager

parent d147632c
No related branches found
No related tags found
No related merge requests found
from assignment2.paxos import Address
from typing import Dict
class LockManager:
def __init__(self) -> None:
self.locks: Dict[int, Address] = dict()
# returns true if lock is acquired or the same client tries to acquire
# a locks it already has, false otherwise
def lock(self, value: int, client: Address) -> bool:
# acquire lock
if value not in self.locks:
self.locks[value] = client
return True
# client already acquired this lock before
if self.locks[value] == client:
return True
# lock is not available
return False
# returns true if lock is unlocked, false otherwise
def unlock(self, value: int, client: Address) -> bool:
# lock does not exist
if value not in self.locks:
return False
# client is not the owner of the locok
if self.locks[value] != client:
return False
# unlock
del self.locks[value]
return True
# quick_test
#if __name__ == "__main__":
#lm = LockManager()
#ca = ("hello", 1234)
#cb = ("hello", 5678)
#assert lm.lock(1, ca) == True
#assert lm.lock(2, cb) == True
#assert lm.lock(1, ca) == True
#assert lm.lock(1, cb) == False
#assert lm.unlock(1, cb) == False
#assert lm.unlock(1, ca) == True
#assert lm.unlock(2, cb) == True
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment