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

相关内容

热门资讯

黑科技辅助!wepoke透明黑... 黑科技辅助!wepoke透明黑科技,(轰趴大菠萝)切实是有挂,详细教程(了解有挂);轰趴大菠萝最新版...
黑科技辅助!wepoke有挂真... 黑科技辅助!wepoke有挂真的有挂,(WePoKe讲解)都是真的是有挂,揭秘教程(有挂细节);详细...
黑科技辅助!wepoke透明黑... 黑科技辅助!wepoke透明黑科技,(WePoKe俱乐部)其实真的是有挂,科技教程(的确有挂)是一款...
黑科技辅助!wepoke辅助插... 黑科技辅助!wepoke辅助插件,(悟空黑桃ai)切实存在有挂,必赢方法(有挂教学)是一款可以让一直...
黑科技辅助!wepoke辅助插... 黑科技辅助!wepoke辅助插件安装,(Wepoke必备)先前真的有挂,透视教程(有挂攻略)是一款可...
黑科技辅助!wepoke黑科技... 您好,WePoKe俱乐部这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家...
黑科技辅助!wepoke辅助插... 您好:智星德州菠萝推荐这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
黑科技辅助!wepoke有挂真... 黑科技辅助!wepoke有挂真的有挂,(fishpoker正规)真是有挂,2025教程(有挂规律);...
黑科技辅助!wepokeai代... 黑科技辅助!wepokeai代打,(Wepoke是真的)总是有挂,可靠教程(有挂规律);Wepoke...
黑科技辅助!wepoke黑科技... 黑科技辅助!wepoke黑科技ai设备,(WePoKe规律)一向是真的有挂,存在挂教程(有挂辅助);...