[英]python multiprocessing pool
使用 python 多處理池時提交了多少作業?
它是如何決定的? 我們能以某種方式控制它嗎? 最多喜歡隊列中最多 10 個作業,以減少 memory 的使用。
假設我有如下編寫的主干代碼:對於每個 chrom 和模擬,我將數據讀取為 pandas dataframe。
(我認為在提交作業之前讀取數據會更好,以減少工作進程中的 I/O 綁定)
然后我將 pandas dataframe 發送給每個工人進行處理。
但似乎提交的作業數量多於最終確定的作業數量,這導致 memory 錯誤。
numofProcesses = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=numofProcesses)
jobs=[]
all_result1={}
all_result2={}
def accumulate(result):
result1=result[0]
result2=result[1]
accumulate(resulst1,all_result1)
accumulate(resulst2,all_result2)
print('ACCUMULATE')
for each chr:
for each sim:
chrBased_simBased_df= readData(chr,sim)
jobs.append(pool.apply_async(func, args=(chrBased_simBased_df,too,many,),callback=accumulate))
print('Submitted job:%d' %(len(jobs)))
pool.close()
pool.join()
有沒有辦法擺脫它?
multiprocessing.Pool
和concurrent.futures.ProcessPoolExecutor
都不允許限制您提交給工作人員的任務數量。
不過,這是一個非常簡單的擴展,您可以使用 Semaphore 自行構建。
您可以查看此gist中的示例。 它使用concurrent.futures
模塊,但將其移植到multiprocessing.Pool
也應該很簡單。
from threading import BoundedSemaphore
from concurrent.futures import ProcessPoolExecutor
class MaxQueuePool:
"""This Class wraps a concurrent.futures.Executor
limiting the size of its task queue.
If `max_queue_size` tasks are submitted, the next call to submit will block
until a previously submitted one is completed.
"""
def __init__(self, executor, max_queue_size, max_workers=None):
self.pool = executor(max_workers=max_workers)
self.pool_queue = BoundedSemaphore(max_queue_size)
def submit(self, function, *args, **kwargs):
"""Submits a new task to the pool, blocks if Pool queue is full."""
self.pool_queue.acquire()
future = self.pool.submit(function, *args, **kwargs)
future.add_done_callback(self.pool_queue_callback)
return future
def pool_queue_callback(self, _):
"""Called once task is done, releases one queue slot."""
self.pool_queue.release()
if __name__ == '__main__':
pool = MaxQueuePool(ProcessPoolExecutor, 8)
f = pool.submit(print, "Hello World!")
f.result()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.