如何解决如何编写一个线程安全的程序使 n 元树在 python 中保持一致
上次我有一个关于可锁定树的面试问题,其中如果树的祖先没有锁定,其子节点也没有锁定,则可以锁定树的节点。
我现在的问题是我必须使这个程序线程安全。
我用了很多概念,但面试官给了我一个提示,我可以使用一些额外的变量来解决这个问题。
我的代码如下。我在互联网上找不到与此问题相关的任何相关文章。我希望你能帮到我。
我的代码如下。
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())
树需要一致,如果两个线程发生冲突,我们可以杀死两个线程或杀死其中一个线程。
- 两个线程可以一起失败,但无论如何都不能同时通过。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。