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之外,这个线程不能接收任何其他的异常,这意味着所有的例外都需要被捕获并妥善处理。

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...