我正在尝试将我长期运行的一个任务并行化。因为某些原因,它不会结束,永远挂着。在
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。在
在
get()
生成结果之前,您正在对所有进程调用join()
。当队列的缓冲区填满时,当数据被刷新到底层管道时,它可能会阻塞。如果join()
一个进程以这种方式被阻止在使用者进程中,则会出现死锁,因为该进程只能在写入所有数据后退出。在将join调用移动到
main()
的末尾,然后它应该可以工作了:相关问题 更多 >
编程相关推荐