[英]How to cleanly sleep indefinitely?
我的代码中启动了几个线程,我需要在脚本结尾无限期地休眠,而这种休眠不会对性能产生重大影响1 。
一种可能是无限循环无限睡眠:
while True:
time.sleep(1)
或睡了很久
time.sleep(4000000)
要么
import signal
signal.pause()
但:
我没有找到睡眠可以接受的最大时间( sys.maxint
太大)
signal.pause()
仅在Unix中实现
而第一个“睡眠循环”对我来说看起来并不干净(为什么是1秒而不是10秒或0.1?)
有没有一种干净的,Python式的无限期睡眠方式?
1我不直接控制线程,否则我会去使用threading.Thread.join()
因为线程本身不会结束。
threading.enumerate
为您提供了所有正在运行的线程(包括主线程)的列表,因此您可以执行以下操作:
main_thread = threading.main_thread()
while True:
L = threading.enumerate()
L.remove(main_thread) # or avoid it in the for loop
for t in L:
t.join()
如果您的库在等待当前线程完成时创建新线程,则需要使用while True
。
假设在enumerate
运行时没有创建线程,则可以检查L
是否只有一个元素(主线程),如果有,则中断循环。 结合Tadhg McDonald-Jensen的建议 ,将iter
与前哨一起使用,结果是:
main_thread = threading.main_thread()
main_threads = [main_thread, ] # WARN: can't have more than one thread here
for threads in iter(threading.enumerate, main_threads):
for t in threads:
if t == main_thread:
continue
t.join()
enumerate
以未定义的顺序返回列表,因此,如果您有多个“主”线程,顺序就变得很重要。 一种解决方案是使用集合 ,即main_threads = {main_thread, }
和iter(lambda : set(threading.enumerate()), main_threads)
。
如果您更喜欢请求宽恕而不是许可的EAFP方法,并且在脚本结束时启动了所有线程,那么您也可以这样做:
for thread in threading.enumerate():
try:
thread.join()
except RuntimeError:
# trying to join the main thread, which would create a deadlock (see https://docs.python.org/3/library/threading.html#threading.Thread.join for details)
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.