问题
In below situation I've created a default pool with two workers and perform tasks. During task processing the task_queue is checked regularly so it doesn't exceeds a certain length limit and prevents up/down stream clutter. How to add dynamically more workers to reduce the task queue length?
import multiprocessing as mp
... code snippet...
def main(poolsize, start_process):
pool = mp.Pool(processes=poolsize, initializer=start_process)
done = False
task_queue = []
while True:
... snippet code : do something ...
if len(task_queue) >= 10:
... code to expand pool goes here...
if done == True:
break
.. do final something ...
if __name__ == '__main__':
# freeze_support()
poolsize = 2
main(poolsize)
回答1:
To add more workers during a running pool processing job you can add below function within the while-loop:
def repopulate(pool, add_workers):
current_pool_size = len(pool._pool) # _.pool gets the current pool size.
new_pool_size = current_pool_size + add_workers
pool._processes = new_pool_size
pool._repopulate_pool()
return pool
Within the while-loop from main()
:
if len(task_queue) >= 10:
new_workers = 2
repopulate(poolname, new_workers)
来源:https://stackoverflow.com/questions/60149376/how-to-add-specific-number-of-additional-workers-to-an-exisiting-multiprocessing