[英]How to run multiple process simultaneously?
我有一個流程非常耗時的循環,而不是等待每個流程完成才能移動到下一次迭代,是否可以運行該流程並直接移動到下一次迭代而不等待它完成?
示例:給定文本,腳本應嘗試從 Web 和本地磁盤中查找匹配的鏈接。 兩者都只返回一個鏈接或路徑列表。
for proc in (web_search, file_search):
results = proc(text)
yield from results
我的解決方案是在完成工作時使用計時器。 如果時間超過等待時間,則應將流程移至托盤並要求從那里開始工作。 現在我將進行下一次迭代並重復相同的操作。 在我的循環結束后,我將從移動到托盤的過程中收集結果。
對於簡單的情況下,如果目標是同時讓每一個過程來看,我們可以使用Thread
的threading
模塊。 所以我們可以像這樣解決這個問題,我們把每個進程作為一個Thread
並要求它把它的結果放在一個列表或其他一些集合中。 代碼如下:
from threading import Thread
results = []
def add_to_collection(proc, args, collection):
'''proc is the function, args are the arguments to pass to it.
collection is our container (here it is the list results) for
collecting results.'''
result = proc(*args)
collection.append(result)
print("Completed":, proc)
# Now we do our time consuming tasks
for proc in (web_search, file_search):
t = Thread(target=add_to_collection, args=(proc, ()))
# We assume proc takes no arguments
t.start()
對於復雜的任務,如評論中所述,最好使用multiprocessing.pool.Pool
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.