I had an interview question last time about lockable trees in which a node of a tree can be locked if its ancestors are not locked and also its children are not locked.
The problem I have now is that I have to make this program thread-safe.
I used so many concepts but the interviewer gave me a hint that I can solve this problem using some extra variables.
My code is given below. I couldn't find any relevant articles related to this problem on the internet. I hope you have something to help me.
My code is given below.
import threading
lock = threading.Lock()
class Lockable(threading.Thread):
def __init__(self,parent):
self.parent = parent
self.locked = False
threading.Thread.__init__(self)
self.lockedDescendents = 0
def mutate_lock(self,delim):
with lock:
self.locked = delim
def mutate_locked_descendents(self,delim,ancestor):
with lock:
ancestor.lockedDescendents+=delim
def lock(self):
if(self.locked):
return True
if(self.lockedDescendents >0):
return False
ancestor = self.parent
while(ancestor):
with lock:
if(ancestor.locked):
return False
ancestor = ancestor.parent
while(ancestor):
self.mutate_locked_descendents(1,ancestor)
ancestor = ancestor.parent
self.mutate_lock(True)
return True
def unlock(self):
if(not self.locked):
return False
ancestor = self.parent
while(ancestor):
self.mutate_locked_descendents(-1,ancestor)
ancestor = ancestor.parent
self.mutate_lock(False)
return True
c = Lockable(None)
a = Lockable(c)
b = Lockable(c)
d = Lockable(a)
e = Lockable(b)
print(a.lock())
print(b.lock())
print(a.unlock())
print(e.lock())
print(d.lock())
The tree needs to be consistent and if two threads collide we can kill both the threads or kill one of the threads.
- both threads can fail together but both of them must not concurrently pass together at any cost.