I’m running Django, and I’m creating threads that run in parallel while Django runs. Those threads sometimes run external processes that block while waiting for external input.
When I restart Django, those threads that are blocking while awaiting external input sometimes persist through the restart, and further they have and keep open Port 8080 so Django can’t restart.
If I knew when Django was restarting, I could kill those threads. How can I tell when Django is restarting so that I can kill those threads (and their spawn).
It wasn’t obvious from django.utils.autoreload where any hooks may be to tell when a restart is occurring.
Is there an alternative way to kill these threads when Django starts up?
Thanks for reading.
Brian
It’s not easy for a Python process to kill its own threads — even harder (nearly impossible) to kill the threads of another process, and I suspect the latter is the case you have… the “restart” is presumably happening on a different process, so those threads are more or less out of bounds for you!
What I suggest instead is “a stitch in time saves nine”: when you create those threads, make sure you set their
daemonproperty toTrue(see the docs — it’s thesetDaemonmethod in Python <= 2.5). This way, when the main thread finishes, e.g. to restart in another process, so will the entire process (which should take all the daemon threads down, too, automatically!-)