Python: Pass or Sleep for long running processes?


Python Problem Overview

I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like:

while True:


while True:

Which one will have the least impact on a system? What is the preferred way to do nothing, but keep a python app running?

Python Solutions

Solution 1 - Python

I would imagine time.sleep() will have less overhead on the system. Using pass will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended.

EDIT: just to prove the point, if you launch the python interpreter and run this:

>>> while True:
...     pass

You can watch Python start eating up 90-100% CPU instantly, versus:

>>> import time 
>>> while True:
...     time.sleep(1)

Which barely even registers on the Activity Monitor (using OS X here but it should be the same for every platform).

Solution 2 - Python

Why sleep? You don't want to sleep, you want to wait for the threads to finish.


# store the threads you start in a your_threads list, then
for a_thread in your_threads:

See: thread.join

Solution 3 - Python

If you are looking for a short, zero-cpu way to loop forever until a KeyboardInterrupt, you can use:

from threading import Event


Note: Due to a bug, this only works on Python 3.2+. In addition, it appears to not work on Windows. For this reason, while True: sleep(1) might be the better option.

For some background, Event objects are normally used for waiting for long running processes to complete:

def do_task():
    print('Task complete.')

event = Event()


Which prints:

Task complete.

Solution 4 - Python

signal.pause() is another solution, see

> Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Not on Windows. (See the Unix man page signal(2).)

Solution 5 - Python

I've always seen/heard that using sleep is the better way to do it. Using sleep will keep your Python interpreter's CPU usage from going wild.

Solution 6 - Python

You don't give much context to what you are really doing, but maybe Queue could be used instead of an explicit busy-wait loop? If not, I would assume sleep would be preferable, as I believe it will consume less CPU (as others have already noted).

[Edited according to additional information in comment below.]

Maybe this is obvious, but anyway, what you could do in a case where you are reading information from blocking sockets is to have one thread read from the socket and post suitably formatted messages into a Queue, and then have the rest of your "worker" threads reading from that queue; the workers will then block on reading from the queue without the need for neither pass, nor sleep.

Solution 7 - Python

Running a method as a background thread with sleep in Python

    import threading
    import time

    class ThreadingExample(object):
        """ Threading example class
        The run() method will be started and it will run in the background
        until the application exits.

        def __init__(self, interval=1):
            """ Constructor
            :type interval: int
            :param interval: Check interval, in seconds
            self.interval = interval

            thread = threading.Thread(, args=())
            thread.daemon = True                            # Daemonize thread
            thread.start()                                  # Start the execution

        def run(self):
            """ Method that runs forever """
            while True:
                # Do something
                print('Doing something imporant in the background')


    example = ThreadingExample()


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGavin M. RoyView Question on Stackoverflow
Solution 1 - PythonJayView Answer on Stackoverflow
Solution 2 - PythontzotView Answer on Stackoverflow
Solution 3 - PythonMatthew D. ScholefieldView Answer on Stackoverflow
Solution 4 - PythonAdamView Answer on Stackoverflow
Solution 5 - Pythonhernan43View Answer on Stackoverflow
Solution 6 - PythonJohanView Answer on Stackoverflow
Solution 7 - PythonAshish GuptaView Answer on Stackoverflow