我的应用程序无限获取新任务,我创建了一个类来处理所有这些传入任务:
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
关于python - 如何在ThreadPool中等待任何线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63881233/