我的应用无限获取新任务,我创建了一个类来处理所有这些传入任务:
class Executor:
pool: ThreadPool
def __init__(self, pool_size: int):
self.pool = ThreadPool(pool_size)
def start(self):
while True:
self.refresh_args()
self.pool.map(self.handler, self.args)
self.pool.join()
当然,此代码是错误的。问题是我不需要等待池中的所有任务。在Executor
必须尽快到池中添加新的任务,因为至少有一个线程完成的工作。这将是无限循环,并且池中的所有线程必须始终处于繁忙状态。
如何实现这种逻辑?还是我应该寻找另一种不用的方法ThreadPool
?如何在其他软件中实现?
您可以使用multiprocessing.Queue
,通过将任务数作为Queue中最大元素数来传递。
当您将某些内容放入队列中时,该线程将一直等待直到它进入队列。同时,您可以像
while True:
queue.get() # blocks if queue is empty
并将每个元素放在一个新线程中:
class Executor:
pool: ThreadPool
def __init__(self, pool_size: int):
self.elements = multiprocessing.Queue(pool_size)
def start(self):
while True:
self.refresh_args()
element = self.elements.get() # blocks if queue is empty
# put element in new thread
# when task is finished, put new element in queue
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句