How does a threading.Thread yield the rest of its quantum in Python?

Tom Future picture Tom Future · Apr 25, 2009 · Viewed 26.7k times · Source

I've got a thread that's polling a piece of hardware.

while not hardware_is_ready():
    pass
process_data_from_hardware()

But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a yield function or something that allows a thread to tell the scheduler "Give the other threads a chance."

while not hardware_is_ready():
    threading.yield()          # This function doesn't exist.
process_data_from_hardware()

But I can't find any reference to something like this in the threading documentation. Python does have a yield statement, but I'm pretty sure that's something else entirely (to do with generators).

What's the correct thing to do here?

Answer

Alex Martelli picture Alex Martelli · Apr 26, 2009

time.sleep(0) is sufficient to yield control -- no need to use a positive epsilon. Indeed, time.sleep(0) MEANS "yield to whatever other thread may be ready".