【发布时间】:2014-02-07 19:00:29
【问题描述】:
根据以下代码,我希望结果列表的长度与多进程提供的项目范围之一相同:
import multiprocessing as mp
def worker(working_queue, output_queue):
while True:
if working_queue.empty() is True:
break #this is supposed to end the process.
else:
picked = working_queue.get()
if picked % 2 == 0:
output_queue.put(picked)
else:
working_queue.put(picked+1)
return
if __name__ == '__main__':
static_input = xrange(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())]
for proc in processes:
proc.start()
for proc in processes:
proc.join()
results_bank = []
while True:
if output_q.empty() is True:
break
else:
results_bank.append(output_q.get())
print len(results_bank) # length of this list should be equal to static_input, which is the range used to populate the input queue. In other words, this tells whether all the items placed for processing were actually processed.
results_bank.sort()
print results_bank
有人知道如何让这段代码正常运行吗?
【问题讨论】:
-
顺便说一句,如果您能帮助我了解是什么让多处理 python 代码对操作系统平台不敏感,我将不胜感激。如果在 Windows 7 或 MacOS 中运行,上述代码的行为会有所不同;在前者中,控制台无响应,而在后者中,结果中的项目重复。
标签: python queue multiprocessing