问题描述
在 python 中,如果我想让进程或线程永远运行,我通常可以用一个空的 while 循环来做到这一点:
In python, if I want to keep a process or thread running forever, I can typically do this with an empty while loop:
while 1:
pass
然而,这会消耗不公平的 CPU 进程.添加一个简短的 sleep
会起作用:
This, however, will eat an unfair amount of CPU process. Adding a short sleep
would work:
import time
while 1:
time.sleep(0.01)
有没有最好或更干净的方法来做到这一点?
Is there any best or cleaner way of doing this?
推荐答案
鉴于相当奇怪的要求(一个不使用太多 CPU 的过程),这是相当紧凑的:
Given the rather bizarre requirements (a process that goes forever without using much CPU), this is reasonably compact:
import threading
dummy_event = threading.Event()
dummy_event.wait()
...但是,我担心我会屈服于解决您的 Y 而不是您的 X 的诱惑.
...however, I fear I am succumbing to the temptation to solve your Y and not your X.
除此之外,如果您的平台不提供 threading
模块,这将不起作用.如果您尝试替换 dummy_threading
模块,dummy_event.wait()
会立即返回.
Besides which, this won't work if your platform doesn't provide the threading
module. If you try to substitute the dummy_threading
module, dummy_event.wait()
returns immediately.
更新:如果您只是为了子进程而保持父进程运行,则可以使用 wait()
Popen 对象,或 join()
方法 Process
对象.这两种方法都会无限期地阻塞,直到子进程结束.如果您正在使用其他一些子流程 API,那么肯定会有等效的功能可用.如果没有,获取进程的 PID 并使用 os.waitpid()
.
Update: if you are just keeping a parent process going for the sake of its subprocesses, you can use the wait()
method on Popen objects, or the join()
method on Process
objects. Both of these methods will block indefinitely until the subprocess ends. If you're using some other subprocess API, there's bound to be equivalent functionality available. If not, get the PID of the process and use os.waitpid()
.
这篇关于实现非阻塞等待的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!