线程休眠时退出进程 [英] Exit a process while threads are sleeping

查看:147
本文介绍了线程休眠时退出进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python脚本中,我启动了一堆线程,每个线程都使用time.sleep(interval)间隔获取一些资源.我正在运行另一个线程,该线程使用cmd模块监视用户输入.当用户输入"q"时,我会致电

In a python script, I started a bunch of threads, each of which pulls some resource at an interval using time.sleep(interval). I have another thread running, which uses the cmd module to monitor user inputs. When the user enters 'q', I call

sys.exit(0)

但是,当脚本正在运行并且我输入'q'时,线程用户输入监视线程已退出,但睡眠线程仍处于活动状态. (表示该程序不会退出)

However, when the script is running and I enter 'q', the thread user input monitoring thread is quit, but the sleeping threads are still alive. (meaning the program does not exit)

我想知道我做对了吗?

推荐答案

sys.exit将仅停止其执行的线程.如果您的程序中还有其他非守护程序线程,它们将继续执行. Python库文档的第17.2.1节包含:

sys.exit will only stop the thread it executes from. If you have other non-daemon thread in your program they will continue to execute. Section 17.2.1 of the Python library docs contains:

可以将线程标记为守护程序" 线".这个标志的意义 是整个Python程序 仅当守护程序线程处于退出状态时退出 左边.初始值是继承的 从创建线程.该标志可以 通过daemon属性设置.

A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

另请参见为什么在Python的线程内调用时,sys.exit()不会退出吗?.

这篇关于线程休眠时退出进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆