在Python中使用多处理递归处理

2024-09-29 10:19:49 发布

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

我正在寻找递归(数据处理)代码的最简单实现,同时利用多个进程。目标功能类似于处理文件夹(-subfolder)结构中的文件,因此有很大的并行空间(同一文件夹中有许多文件),但是递归使事情变得具有挑战性。你知道吗

以下是我迄今为止编写的一段代码:

#coding UTF-8

import multiprocessing as mp
iThreads = mp.cpu_count()

# Dummy data structure; balanced binary tree, numbers are indexes of child nodes
testList = [[1, 2],
            [3, 4], [5, 6],
            [7, 8], [9, 10], [11, 12], [13, 14],
            [15, 16], [17, 18], [19, 20], [21, 22], [23, 24], [25, 26], [27, 28], [29, 30],
            [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],
            ]

m = mp.Manager()
taskList = m.list()

def procList(inListItem):
    taskList.append(inListItem)
    processList = [mp.Process(target=procList, args=(li, )) for li in testList[inListItem]]
    map(mp.Process.start, processList)
    map(mp.Process.join, processList)

    # For Python 3, enforcing looping through iterable map objects:
    # list(map(mp.Process.start, processList))
    # list(map(mp.Process.join, processList))

    # For readability: less dense:
    # processList = []
    # for li in testList[inListItem]:
    #     p = mp.Process(target=procList, args=(li,))
    #     processList.append(p)
    #     p.start()
    # 
    # for p in processList:
    #     p.join()


if __name__ == "__main__":
    procList(0)

    print taskList
  • 理论上讲,演练是深度优先的,但显然多处理会把这搞砸,这不是问题
  • 最初我是想多处理池,但是worker的数量是有限的,如果我没有用这个数量达到完全深度,整个程序就会冻结,我猜(每个worker都在等待另一个worker被释放以达到递归的完全深度)
  • 这段代码是针对python2的。map()函数不会遍历map对象,因此必须对其进行冻结

我要问的是这个代码是否正确(我是一个多处理机noob)


Tags: 代码inmapformpliprocessstart