Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

python - Best way to implement a non-blocking wait?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() 

...however, I fear I am succumbing to the temptation to solve your Y and not your X.

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.

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...