Python多处理清除列表结构?

2024-09-25 04:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多处理脚本,如下所示:

from multiprocessing import Pool

currentDepth = 1
maxDepth = 3
nodeList = []
auxList = []

def grow():
    global nodeList
    global auxList
    while(nodeList):
        print("Iterate on: " + str(nodeList))
        p.map(proc1, nodeList)
        print("Repopulating nodeList: " + str(nodeList) + " from auxList: " + str(auxList))   
        nodeList = list(auxList)

nodeList.append(seed)
p = Pool(8)
grow()

proc1函数调用一个proc2函数,如下所示:

def proc1(currentNode):
     val = int(currentNode.name)*2
     if (val not in visited):
         proc2(currentNode, val, currentNode.depth+1)

def proc2(currentNode, newVal, depth):
    global currentDepth
    global auxList
    print("Next node value: " str(newVal))
    print("Next node depth: " str(depth))
    nextNode = Tree(name='{}'.format(newVal))
    currentNode.add_child(nextNode)
    if depth > currentDepth:
        currentDepth = depth
        print("Current Depth updated: " + str(currentDepth))
        print("Maximum Depth: " + str(maxDepth))
    if depth < maxDepth:
        print("Appending to aux: " + str(nextNode.name)
        auxList.append(nextNode)
        print("auxList: " + str(auxList))

proc2成功地附加到auxList,而auxList又应该在每次迭代中重新填充节点列表,直到达到一定深度。打印输出如下所示:

Iterate on: [Tree node '2' (0x7f3537cd61d)]
Next node value: 4
Node depth: 2
Current Depth updated: 2
Maximum Depth: 3
Appending to aux: 4
auxList: [Tree node '4' (0x7f79abec191)]
Repopulating nodeList: [Tree node '2' (0x7f79ac3171d)] from auxList: []

一切都在正确编译,那么为什么auxList缺少它的条目呢?我对异步执行和globals的使用有一些怀疑,但我不知道问题出在哪里。提前谢谢大家


Tags: fromnodetreeglobalprintdepthstrmaxdepth