Search code examples
pythonpython-3.xmultithreadingdeadlockbusy-waiting

Is it better to deadlock main thread instead of busy waiting?


I have a main thread that starts multiple deamon threads listening to filesystem events. I need to keep the main thread alive. To do so I can use a while loop, or "deadlock" it. Which is better, performance wise?

while True:
    time.sleep(1)

or

from threading import Event
Event().wait()

I can interrupt the main thread using ctrl+c in both cases.

EDIT: Or is there a better way?


Solution

  • With time.sleep(delay) you will have to wait until the end of the sleep time to respond to the event, so the responsiveness of your code depends on the delay time. While with Event().wait() event management your application should be much more responsive as it will immediately respond to the external stimulus without waiting for the end of the delay. On the other hand, however, this also means that the managed ad will have to acquire / release the GIL much more frequently than the time.sleep(delay) that will release the GIL for the delay time. How does this affect performance?
    Depending on the type of application, if you have a lot of active threads, you can probably see some small differences. This problem was particularly evident in Python 2x or earlier versions, in Python 3x these functions are impoverished at low level and the problem is much less obvious.

    If you are interested in learning more about the subject, here you will find the C implementation of the function to acquire the lock using python3.

    I hope I have answered your question fully.