Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
pistacchio Avatar asked Jul 12 '10 07:07

pistacchio


People also ask

Does Waitpid block?

waitpid can be either blocking or non-blocking: If options is 0, then it is blocking.

Is JavaScript blocking or non-blocking?

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.

Why is Node non-blocking?

In Node, non-blocking primarily refers to I/O operations, and JavaScript that exhibits poor performance due to being CPU intensive rather than waiting on a non-JavaScript operation, such as I/O, isn't typically referred to as blocking.

What is the difference between asynchronous and non-blocking concerning Node Js concept?

A nonblocking call returns immediately with whatever data are available: the full number of bytes requested, fewer, or none at all. An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.


1 Answers

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

like image 116
detly Avatar answered Sep 17 '22 18:09

detly