跳转到主要内容

具有无限工作者数量的线程池。

项目描述

无界线程池

python的concurrent.futures.Executor实现,按需创建新线程,并在不再需要时停止它们。

它设计为允许无限递归提交任务,因此以下代码即使在创建10k个线程的情况下也能正常工作

from unbounded_thread_pool import UnboundedThreadPoolExecutor

with UnboundedThreadPoolExecutor() as executor:
    def factorial(n: int):
        if n == 0 or n == 1:
            return 1
        else:
            return executor.submit(factorial, n - 1).result() * n
    print(factorial(10000))

安装

pip install unbounded_thread_pool

需求

  • Python (3.6, 3.7, 3.8)

用法

UnboundedThreadPoolExecutor支持以下构造函数参数

  • name: str:执行器的名称,所有线程名称都以它为前缀。默认为UnboundedThreadPoolExecutor
  • max_thread_idle_time: float:空闲工作线程应存在的秒数。默认为30秒。

有关方法的更多详细信息,请参阅官方Python文档中的concurrent.futures.Executor

asyncio一起使用

当您编写大量同步代码调用异步代码,反之亦然时(例如,如果您使用asgiref sync_to_asyncasync_to_sync),默认的asyncio执行器可能会阻塞。这发生在您有以下代码流的情况下

异步代码 ---> 同步代码(1) ---> 异步代码 ---> 同步代码(2)

在这里,第二个(2)同步代码需要线程池中有空闲的工作者,但线程池可能已经被第一个(1)同步代码耗尽。这会导致死锁,因为(1)等待(2),而(2)等待(1)释放线程池。为了消除这个问题,您可以使用UnboundedThreadPoolExecutor

loop = asyncio.get_running_loop()
loop.set_default_executor(UnboundedThreadPoolExecutor(name='AsyncioExecutor'))

项目详情


下载文件

下载您平台对应的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分发

unbounded-thread-pool-0.2.0.linux-x86_64.tar.gz (6.9 kB 查看哈希值)

上传时间

构建分发

unbounded_thread_pool-0.2.0-py3-none-any.whl (5.3 kB 查看哈希值)

上传时间 Python 3

由以下机构支持