简体   繁体   English

Python 进程是否应该等待使用“run_in_executor”分叉的作业,尽管我没有等待?

[英]Should Python process wait for a job forked using `run_in_executor`, although I did not wait for?

Assume we have the following script:假设我们有以下脚本:


def sync_sleep(x):
    print("sync_sleep going to sleep")
    time.sleep(x)
    print("sync_sleep awake")


async def main():
    loop = asyncio.get_running_loop()
    loop.run_in_executor(None, sync_sleep, 4)
    print("main going to sleep")
    await asyncio.sleep(1)
    print("main awake ")


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    print("main finished")

Note : I have omitted loop.close intentionally.注意:我故意省略loop.close

Now when I execute the above script:现在当我执行上面的脚本时:

python script.py

I have the following output:我有以下 output:

sync_sleep going to sleep
main going to sleep
main awake 
main finished
sync_sleep awake

I expected after running the script, the process to exit after printing "main finished" , but it did not until the job sync_sleep has finished.我预计在运行脚本后,打印"main finished"后进程会退出,但直到作业sync_sleep完成后才退出。 I mean, if I wanted to wait for that job, I would have added the line:我的意思是,如果我想等待那份工作,我会添加以下行:

loop.run_until_complete(loop.shutdown_default_executor())

Is my expectation wrong?我的期望错了吗?

The default ThreadPoolExecutor waits at exit for daemon threads, meaning the process waits for the thread to finish, and only then stops.默认的ThreadPoolExecutor在退出时等待守护线程,这意味着进程等待线程完成,然后才停止。

Apart from implementing an Executor class yourself, there's no option other than using the threading module to create a new thread with daemon=True .除了自己实现一个Executor class 之外,除了使用threading模块使用daemon=True创建一个新线程之外别无选择。 If you wish to wait for that thread in asyncio , you can always run an executor to await the thread.join() .如果你想在asyncio中等待那个线程,你总是可以运行一个执行器来await thread.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM