Python threading interrupt sleep

How about using condition objects: https://docs.python.org/2/library/threading.html#condition-objects

Instead of sleep() you use wait(timeout). To "interrupt" you call notify().


The correct approach is to use threading.Event. For example:

import threading

e = threading.Event()
e.wait(timeout=100)   # instead of time.sleep(100)

In the other thread, you need to have access to e. You can interrupt the sleep by issuing:

e.set()

This will immediately interrupt the sleep. You can check the return value of e.wait to determine whether it's timed out or interrupted. For more information refer to the documentation: https://docs.python.org/3/library/threading.html#event-objects .