Non blocking wait in python

前端 未结 4 1501
忘掉有多难
忘掉有多难 2021-01-04 05:43

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
         


        
4条回答
  •  耶瑟儿~
    2021-01-04 06:28

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

提交回复
热议问题