Asyncio:如何通过另一个协程在ThreadPoolExecutor中终止线程
创始人
2024-09-21 07:30:53
0

在使用ThreadPoolExecutor时,常常需要动态地添加或删除线程。虽然线程本身可以简单地结束,但ThreadPoolExecutor需要一个机制来维护所有线程。一种方法是通过在三个步骤中提供完整的回调API来查询执行的线程,另一种是通过查看内部数据来查询执行的线程。

以下是一种通过内部数据抛出异常来从ThreadPoolExecutor终止线程的示例。

import asyncio
from concurrent.futures import ThreadPoolExecutor

async def main_task():
    loop = asyncio.get_event_loop()
    async with ThreadPoolExecutor() as pool:
        for i in range(2):
            loop.run_in_executor(pool, task, i)

async def task(index):
    try:
        while True:
            print("Task-{} is running...".format(index))
            await asyncio.sleep(1)
    except Exception as e:
        print("Task-{} is interrupted due to {}".format(index, e))

async def stop_task(loop):
    await asyncio.sleep(2)
    tasks = [task1, task2] # get task objects from a global list
    for task in tasks:
        task.cancel()
    loop.stop()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    task1 = loop.create_task(task(1))
    task2 = loop.create_task(task(2))
    loop.create_task(main_task())
    loop.create_task(stop_task(loop))
    loop.run_forever()

在上述示例中,main_task()中使用了ThreadPoolExecutor提供了两个线程来运行task()stop_task()main_task()后面,会在2秒后调用task1task2cancel()方法将两个线程给中止。task()中捕获了asyncio.CancelledError异常,然后可以做一些清理等收尾工作。

运行该脚本,可以看到:

Task-1 is running...
Task-2 is running...
Task-1 is running...
Task-2 is running...
Task-1 is interrupted due to Task was cancelled
Task-2 is interrupted due to Task was cancelled

在取消一个正在执行的线程时,除了抛出asyncio.CancelledError之外,这个线程不能接收任何其他的异常,这意味着所有的例外都需要被捕获并妥善处理。

相关内容

热门资讯

Android Studio ... 要解决Android Studio 4无法检测到Java代码,无法打开SDK管理器和设置的问题,可以...
安装tensorflow mo... 要安装tensorflow models object-detection软件包和pandas的每个...
安装了Laravelbackp... 检查是否创建了以下自定义文件并进行正确的配置config/backpack/base.phpconf...
安装了centos后会占用多少... 安装了CentOS后会占用多少内存取决于多个因素,例如安装的软件包、系统配置和运行的服务等。通常情况...
按照Laravel方式通过Pr... 在Laravel中,我们可以通过定义关系和使用查询构建器来选择模型。首先,我们需要定义Profile...
按照分类ID显示Django子... 在Django中,可以使用filter函数根据分类ID来筛选子类别。以下是一个示例代码:首先,假设你...
Android Studio ... 要给出包含代码示例的解决方法,我们可以使用Markdown语法来展示代码。下面是一个示例解决方案,其...
Android Retrofi... 问题描述:在使用Android Retrofit进行GET调用时,获取的响应为空,即使服务器返回了正...
Alexa技能在返回响应后出现... 在开发Alexa技能时,如果在返回响应后出现问题,可以按照以下步骤进行排查和解决。检查代码中的错误处...
Airflow Dag文件夹 ... 要忽略Airflow中的笔记本检查点,可以在DAG文件夹中使用以下代码示例:from airflow...