python - 如何在ThreadPool中等待任何线程?

标签 python python-3.x multithreading

我的应用程序无限获取新任务,我创建了一个类来处理所有这些传入任务:

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/

相关文章:

python - 为什么 pandas 逻辑运算符不像它应该的那样在索引上对齐?

python - 为什么 2to3 将 mydict.keys() 更改为 list(mydict.keys())?

python-3.x - 减少 return 语句的数量

c# - 何时应处置 ManualResetEvent?

c++ - 破坏线程 vector 段错误

python - django paginator - 如何显示所有可用的页码

python - 文件存在测试: fast subtree search in python

python - 使用 PyMongo,如何使用 create_index() 导入通过 index_information() 导出的索引?

python-3.x - 更改数据表示后维度不匹配 "LabelBinarizer "

ios - 如何仅在从网络获取数据后显示tableView? ( swift )