python中的非阻塞等待 [英] Non blocking wait in python

查看:1046
本文介绍了python中的非阻塞等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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进程数量.增加短暂的睡眠会起作用

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 and cleaner way of doing this? Thanks

推荐答案

鉴于相当奇怪的要求(一个无需使用大量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.

更新:如果您只是为了使其子流程保持父流程的正常进行,则可以使用打开对象,或 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().

这篇关于python中的非阻塞等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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