Python多处理为什么我的进程没有返回/完成?

2024-09-27 00:11:53 发布

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

我正在尝试将我长期运行的一个任务并行化。因为某些原因,它不会结束,永远挂着。在

import multiprocessing as mp

class PartitionedResult(object):
    index = 0
    P = []
    def __init__(self, index, P):
        self.index = index
        self.P = P        


def longRunningTask(index, output):
    P = []
    for i in range (0, 1000):        
        print(i)
        P.append(i)

    print("I'm done!")
    output.put(PartitionedResult(index, P))
    return

def main():
    output = mp.Queue()
    processes = [mp.Process(target=longRunningTask, args=(x,output,)) for x in range(4)]
    for p in processes:
        p.start()

    for p in processes:
        p.join()

    results = [output.get() for p in processes]
    print("This never shows up")



if __name__ == '__main__':
    main()

它正在打印数字0-999每4个过程,它甚至达到“我完成了!”行,但它无法到达results = [output.get() for p in processes]

如果我把for循环的范围缩小到range(0,50),它会突然起作用。在

有什么问题吗?在

编辑:我在Windows10上使用了Python3.4,我在两台不同的计算机上尝试了它,并删除了pycache。在


Tags: inselfforoutputgetindexmaindef
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:53

get()生成结果之前,您正在对所有进程调用join()。当队列的缓冲区填满时,当数据被刷新到底层管道时,它可能会阻塞。如果join()一个进程以这种方式被阻止在使用者进程中,则会出现死锁,因为该进程只能在写入所有数据后退出。在

将join调用移动到main()的末尾,然后它应该可以工作了:

def main():
    output = mp.Queue()
    processes = [mp.Process(target=longRunningTask, args=(x,output,)) for x in range(4)]

    for p in processes:
        p.start()  

    results = [output.get() for p in processes]
    print("This never shows up")

    for p in processes:
        p.join()

相关问题 更多 >

    热门问题