從下面的代碼中,我期望結果列表的長度與多進程所在的項目範圍之一相同:Python多重處理的輸出隊列提供了比預期更多的結果
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中運行,上述代碼的行爲會有所不同;在前者中,控制檯不響應,而在後者中重複結果中的項目。 – Jaqo