2

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?

Julien__
  • 1,962
  • 1
  • 15
  • 25

1 Answers1

2

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.

Massifox
  • 4,369
  • 11
  • 31
  • Thanks for answering. Can you expand on *"this also means that the managed ad will have to acquire / release the GIL much more frequently"*? I don't think the main thread acquires the GIL, otherwise how could my other threads run at the same time? – Julien__ Sep 23 '19 at 08:40
  • Event.wait is implemented in Python using a lot of small time-sleep calls implemented in C. Each call to sleep requires to acquire / release the lock. if you like, then I'll add the code for the implementation of wait (), so you better understand what I mean – Massifox Sep 23 '19 at 09:45
  • ah... So let's say they use some time delta `delta`. I could just do `while True: sleep(delta)` and get something equivalent without acquiring the GIL? – Julien__ Sep 23 '19 at 09:47
  • Actually the last part of my question seem even more relevant now: can't I just wait for the keyboard interrupt without looping? – Julien__ Sep 23 '19 at 09:48
  • the answer is: it depends on what you have to do. Surely in most cases the best option is to use wait (): the application will be more reactive. However in some cases, when the number of threads is very high, it could benefit the performance of your application to use sleep () with sleep time slightly higher than the default wait (). – Massifox Sep 23 '19 at 10:20
  • 1
    okay, I only have two threads so i'll just keep using the wait. Thanks – Julien__ Sep 23 '19 at 10:33