[英]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.