首页 > 解决方案 > 如何为 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())

树需要保持一致,如果两个线程发生冲突,我们可以杀死两个线程或杀死其中一个线程。

标签: pythonmultithreadingthread-safetypython-multithreading

解决方案


推荐阅读