我怎麼能腳本,使用兩個隊列,這些的?: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