在默认执行器中的任务仍在运行时退出程序

2024-04-20 02:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序可以执行一些长时间运行的同步任务,即使其中一些任务还没有完成,也可能需要退出。下面是一个在main()中启动这样一个任务的简单程序。main()之后立即返回,因此程序应该退出。

import asyncio, time

def synchronous_task():
    for i in range(5):
        print(i)
        time.sleep(1)

async def main():
    loop.run_in_executor(None, synchronous_task)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

print('Main thread exiting.')

但我在运行脚本时得到的却是:

^{pr2}$

如何处理这种情况?事件循环的默认执行器已经使用守护进程线程,在我的例子中,不进行清理就终止程序是可以的,但是我不想使用os._exit()


Tags: runinimport程序loopasynciofortask
1条回答
网友
1楼 · 发布于 2024-04-20 02:12:01

你的问题更多的是关于如何杀死一根线。查找this帖子了解详细信息。在

事件的解决方案是:

import asyncio, time
from functools import partial
import threading
import concurrent


def synchronous_task(ev):
    for i in range(5):
        if ev.isSet():
            print('terminating thread')
            return
        print(i)
        time.sleep(1)

async def main():
    ev = threading.Event()  # see: https://stackoverflow.com/a/325528/1113207

    loop.run_in_executor(None, partial(synchronous_task, ev))
    await asyncio.sleep(2)  # give thread some time to execute, to see results

    ev.set()


loop = asyncio.get_event_loop()
executor = concurrent.futures.ThreadPoolExecutor(5)
loop.set_default_executor(executor)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    executor.shutdown(wait=True)  # see: https://stackoverflow.com/a/32615276/1113207
    loop.close()

print('Main thread exiting.')

结果:

^{pr2}$

相关问题 更多 >