0

I need my main program, at some point, to do nothing - forever (there are threads started earlier which do some work).

I was wondering what was the pythonic way to do so. I particularly would like to avoid losing CPU cycles on this nothingness.

My immediate guess was time.sleep(100000) where 100000 is large enough for the life of my program. It works but is not aesthetically pleasant. I checked the CPU load of a python session running this: not measurable (close to zero).

I also tried

while True:
    pass

It looks nicer but the hit on the CPU is enormous (~25%).

Is there one-- and preferably only one --obvious way to do it?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Please notice that you still need to use `while True: …` for `time.sleep()`, because signals (such as a terminated child) [can break the timeout](https://docs.python.org/2/library/time.html#time.sleep) (fixed in 3.5). – Kijewski Nov 23 '15 at 15:41

1 Answers1

5

If you would like to wait for the thread to exit, use thread.join():

join([timeout])

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

Example usage:

import threading
t = threading.Thread(name='non-daemon', target=non_daemon)

t.start() # This will not block
t.join() #  This is blocking
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69