首页 > 解决方案 > 在 Python 中使用多处理进行递归处理

问题描述

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

这是我到目前为止生成的一段代码:

#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 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()

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

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

    print taskList

我要问的是这段代码是否正确(我是一个多处理菜鸟)

标签: pythonrecursionmultiprocessingpython-2.x

解决方案


推荐阅读