Asyncio:如何通过另一个协程在ThreadPoolExecutor中终止线程
创始人
2024-09-21 07:30:45
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之外,这个线程不能接收任何其他的异常,这意味着所有的例外都需要被捕获并妥善处理。

相关内容

热门资讯

推荐透视!hardrock透视... 推荐透视!hardrock透视工具!果然是真的有辅助插件(有挂教程)-哔哩哔哩1、hardrock透...
总结透视!wepoker辅助器... 总结透视!wepoker辅助器软件下载,hhpoker的辅助是真的吗,模块教程(有挂分享)-哔哩哔哩...
科普透视!epoker透视!真... 科普透视!epoker透视!真是真的是有辅助插件(有挂解惑)-哔哩哔哩1、游戏颠覆性的策略玩法,独创...
必备透视!德州透视是真的吗,w... 必备透视!德州透视是真的吗,wpk免费辅助,项目教程(证实有挂)-哔哩哔哩1、用户打开应用后不用登录...
教你透视!werplan怎么作... 教你透视!werplan怎么作必弊!竟然是有辅助教程(有挂秘诀)-哔哩哔哩教你透视!werplan怎...
详情透视!智星德州插件怎么下载... 详情透视!智星德州插件怎么下载,德普之星透视软件免费入口官网,要领教程(有挂技巧)-哔哩哔哩1、下载...
专业透视!pokermaste... 专业透视!pokermaster修改器!原来一直都是有辅助攻略(有挂分享)-哔哩哔哩1、pokerm...
总结透视!wepoker透视最... 总结透视!wepoker透视最简单三个步骤,wepoker私局辅助,窍门教程(有挂辅助)-哔哩哔哩;...
了解透视!红龙poker辅助器... 了解透视!红龙poker辅助器免费观看!竟然真的是有辅助脚本(证实有挂)-哔哩哔哩1)红龙poker...
揭幕透视!hhpoker有作必... 揭幕透视!hhpoker有作必弊的吗,wejoker手机版透视脚本,总结教程(了解有挂)-哔哩哔哩1...