首页 > 解决方案 > 不能使用从 Python 多处理返回的值

问题描述

我在一个类中的一个方法中使用了多处理技术(该类最终会被导入到主类中执行),代码段如下

        result = []
        if __name__ == '__main__':
            pool = multiprocessing.Pool(processes=4)
            data = [[1,2],[3,4],[5,6],[7,8]]
            result_m = [pool.starmap(some_function, data)]
            pool.join()
            pool.close()
            result.append(result_m[0])
            result.append(result_m[1])
            result.append(result_m[2])
            result.append(result_m[3])
        first = result[0]
        sceond = result[1]
        third = result[2]
        fourth = result[3]

基本上,这个想法是使用多处理在四个进程中同时调用另一个名为 some_function() 的方法,然后将每个进程的结果附加到名为“result”的列表中。但是,当我运行代码时,最后四行总是显示“列表索引超出范围”。结果似乎从未添加到之前定义的列表中。我想知道为什么会这样,有什么潜在的方法可以解决这个问题?谢谢!

标签: pythonpython-multiprocessing

解决方案


推荐阅读