WoJ*_*WoJ 4 python sleep python-3.x thread-sleep
我的代码中启动了一些线程,我需要在脚本结束时无限期地休眠,而这种休眠不会对性能造成重大影响1。
一种可能性是无限循环并短暂睡眠:
while True:
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
或者睡很长时间
time.sleep(4000000)
Run Code Online (Sandbox Code Playgroud)
或者
import signal
signal.pause()
Run Code Online (Sandbox Code Playgroud)
但:
我没有找到睡眠可以接受的最大时间(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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3071 次 |
| 最近记录: |