我怎么能脚本,使用两个队列,这些的?:Python的多与更新队列和输出队列
- 一个作为与一些数据开始工作队列,取决于一个Python多进程要并行执行的功能条件,可以动态地接收进一步的任务,另一个收集结果并在处理完成后用于记录结果。
我基本上需要在工作队列中放置更多的任务,这取决于我在其初始项目中找到的内容。我在下面发表的例子很愚蠢(我可以根据自己的喜好将其转换为输出队列),但其机制很清晰,并反映了我需要开发的一部分概念。
特此我尝试:
import multiprocessing as mp
def worker(working_queue, output_queue):
item = working_queue.get() #I take an item from the working queue
if item % 2 == 0:
output_queue.put(item**2) # If I like it, I do something with it and conserve the result.
else:
working_queue.put(item+1) # If there is something missing, I do something with it and leave the result in the working queue
if __name__ == '__main__':
static_input = range(100)
working_q = mp.Queue()
output_q = mp.Queue()
for i in static_input:
working_q.put(i)
processes = [mp.Process(target=worker,args=(working_q, output_q)) for i in range(mp.cpu_count())] #I am running as many processes as CPU my machine has (is this wise?).
for proc in processes:
proc.start()
for proc in processes:
proc.join()
for result in iter(output_q.get, None):
print result #alternatively, I would like to (c)pickle.dump this, but I am not sure if it is possible.
这并没有结束,也没有打印任何结果。
在整个过程结束时,我想确保工作队列是空的,并且所有并行函数都在迭代后取出结果之前写入输出队列。你有如何使其工作的建议?
谢谢!我将在问题中编辑这个。 – Jaqo
不客气!请不要在你这样做的时候编辑我的回复,开始处理你问题的其余部分。 – tawmas
我刚刚读了你答案的其余部分。我会尝试应用一段时间True循环。我想知道如果队列中没有更多项目可以处理,那么过程是否完成。我想使用类似队列长度的东西,但文档声明这是不可靠的。 – Jaqo