python - 如何为 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())
树需要保持一致,如果两个线程发生冲突,我们可以杀死两个线程或杀死其中一个线程。
- 两个线程可以一起失败,但它们不能不惜一切代价同时通过。
解决方案
推荐阅读
- sql - 我正在尝试从 sql server 中的列中获取特定值但出现错误
- c# - 如何在 C# WinForm 中实现“office 2016 文件菜单”
- java - 为什么转换为 int 给我 8 而不是 0?
- c# - pdf文件上不同类型的签名
- java - 使用 java 和 selenium 3 的边缘铬无头模式
- java - 对 Oracle Db 使用准备语句,违反唯一约束
- r - R用ifelse改变多列
- ios - 没有名为“FlutterPlugin”的类型或协议
- python - 如何在 python 的输出中显示我的程序代码?
- node.js - ReferenceError:未定义窗口 Angular Universal