Python 3 中的递归和多线程冲突
Recursivity and multithread collisions in Python 3
下午好
我正在尝试将我的递归函数修改为多线程递归函数以减少处理时间。
我已经在需要的地方实现了 RLock 对象。
我的递归函数必须打印一个包含 98 行的嵌套数组,但使用多线程有时会发生冲突,我无法检索所有节点。
(配合同步方式使用)
我已尝试重现我的代码的行为:
class Foo(object):
def __init__(self, name):
self.name = name
self.nodes = []
self.lock = threading.RLock()
class Git(object):
def __init__(self):
self.lock = threading.RLock()
git = Git()
def getChildrenFiles(node):
with node.lock:
with git.lock:
# sending some commandes to git repository and get some files
pass
myRecursiveFunction(child, False)
def myRecursiveFunction(foo, async=True):
with foo.lock:
# (Simulation) Retrieving Foo children name from local files
foo.nodes.append(Foo(....))
if not foo.nodes:
return
pool = ThreadPool(os.cpu_count())
if async:
results = []
for fooChildren in foo.nodes:
results.append(pool.apply_async(getChildrenFiles, (fooChildren,)))
all(res.get() for res in results)
else:
for fooChildren in foo.nodes:
pool.apply(getChildrenFiles, (fooChildren,))
pool.close()
pool.join()
if __name__ == "__main__":
foo = Foo("MyProject")
myRecursiveFunction(foo)
'''print foo as Tree Like :
Foo-A
Foo-B
Foo-C
Foo-E
Foo-K
'''
谢谢
我终于找到问题了,它对我的程序来说非常具体,但我仍然会尝试解释它。
说明
在函数 getChildrenFiles 中,我为 git 对象使用了锁,并且 git 对象被声明为全局变量。
问题是我发送了一些命令,例如:
def getChildrenFiles(node):
with node.lock:
with git.lock:
sendCommand(....)
.....
with git.lock:
sendOtherCommand(....)
myRecursiveFunction(child, False)
并且在第一个命令和第二个命令之间,另一个线程锁定了 git 对象,并且第一个线程中 git 对象使用的一些文件在另一个线程中被更改。然后引发了自定义异常。
下午好
我正在尝试将我的递归函数修改为多线程递归函数以减少处理时间。
我已经在需要的地方实现了 RLock 对象。
我的递归函数必须打印一个包含 98 行的嵌套数组,但使用多线程有时会发生冲突,我无法检索所有节点。
(配合同步方式使用)
我已尝试重现我的代码的行为:
class Foo(object):
def __init__(self, name):
self.name = name
self.nodes = []
self.lock = threading.RLock()
class Git(object):
def __init__(self):
self.lock = threading.RLock()
git = Git()
def getChildrenFiles(node):
with node.lock:
with git.lock:
# sending some commandes to git repository and get some files
pass
myRecursiveFunction(child, False)
def myRecursiveFunction(foo, async=True):
with foo.lock:
# (Simulation) Retrieving Foo children name from local files
foo.nodes.append(Foo(....))
if not foo.nodes:
return
pool = ThreadPool(os.cpu_count())
if async:
results = []
for fooChildren in foo.nodes:
results.append(pool.apply_async(getChildrenFiles, (fooChildren,)))
all(res.get() for res in results)
else:
for fooChildren in foo.nodes:
pool.apply(getChildrenFiles, (fooChildren,))
pool.close()
pool.join()
if __name__ == "__main__":
foo = Foo("MyProject")
myRecursiveFunction(foo)
'''print foo as Tree Like :
Foo-A
Foo-B
Foo-C
Foo-E
Foo-K
'''
谢谢
我终于找到问题了,它对我的程序来说非常具体,但我仍然会尝试解释它。
说明
在函数 getChildrenFiles 中,我为 git 对象使用了锁,并且 git 对象被声明为全局变量。
问题是我发送了一些命令,例如:
def getChildrenFiles(node):
with node.lock:
with git.lock:
sendCommand(....)
.....
with git.lock:
sendOtherCommand(....)
myRecursiveFunction(child, False)
并且在第一个命令和第二个命令之间,另一个线程锁定了 git 对象,并且第一个线程中 git 对象使用的一些文件在另一个线程中被更改。然后引发了自定义异常。