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秒后调用task1和task2的cancel()方法将两个线程给中止。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之外,这个线程不能接收任何其他的异常,这意味着所有的例外都需要被捕获并妥善处理。

相关内容

热门资讯

揭秘教程!wepoker辅助透... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
透明挂教程!wepoker有辅... 『标题:当前标题』主打赛后复盘的 AI 游戏攻略黑科技走红,对局总结能力开挂。上传对局回放或者战绩截...
发现一款!!wepoker代打... 很多人使用云端 AI 时,都担心wepoker代打辅助、内部资料上传带来隐私风险。这款本地运行的 A...
2026教程!wpk私人局有透... 很多人使用云端 AI 时,都担心wpk私人局有透视吗、内部资料上传带来隐私风险。这款本地运行的 AI...
可靠教程!德扑之星透视辅助软件... 可靠教程!德扑之星透视辅助软件激活码,wepoker是不是有挂插件(本来存在有开挂)AI 是一款可以...
我来教教大家!微扑克透视脚本,... 我来教教大家!微扑克透视脚本,WPK到底有挂吗助手(原生真的是有辅助挂)主打本地运行的 AI 黑科技...
大家学习交流!wepokerp... 您好,大家学习交流!wepokerplus辅助,微扑克怎么开挂教程(最初真的是有开挂)这款游戏可以开...
新手必备!wepoker手机版... 很多人使用云端 AI 时,都担心wepoker手机版辅助、内部资料上传带来隐私风险。这款本地运行的 ...
技巧教程!wepoker透视脚... 一款 AI 游戏攻略黑科技工具上线,查攻略效率直接开挂。它整合版本更新、装备搭配、BOSS 打法、牌...
必赢方法!wepoker数据分... 您好:wepoker数据分析工具这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...