您應該閱讀約pool.map_async,我已經多次使用它來執行異步任務。 基本上你需要做的是寫一個函數,它傳遞2個參數,in_file和out_file,實例化該池並將其與函數及其元組參數[(in_file1,out_file1),(in_file2,out_file2) ...]。
小心!雖然文件可能不會重疊,但您仍在使用IO設備,這在等待讀取和寫入方面會產生大量開銷,因此嘗試將文件的讀取和寫入與主邏輯分開,即讀取文件,處理所有文件的數據並將其存儲在RAM上,然後將文件寫出。
編輯1:在python3中顯示他們有starmap,根據我的理解,您可以傳遞可迭代的迭代,迭代被解析爲參數。所以我改變了代碼以使用starmap。 另外,您應該考慮在一次迭代中添加超時,您可以使用get method來實現。
我會包括一些示例代碼(它在python2但邏輯/語法是很容易轉移):
import multiprocessing as mp
def foo(in_file, out_file):
in_data = ""
# this is just an example of how to read file
with open(in_file, "rb") as f:
for line in f:
in_data += line
...
out_data = process(in_data)
...
with open(out_file,'wb') as f:
f.write(out_data)
def main():
files =[("/infile1", "/outfile1"), ("/infile2", "/outfile2"), ...]
# you should choose how many processes you wish to instantiate.
# leaving it blank will assume the number of threads/core available.
pool = mp.Pool(processes=4)
pool.starmap_async(foo,files)