views:

71

answers:

2

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

A: 

What are you using to restart django? I'd put something in that script to look for process id's in the socket file(s) and kill those before starting django.

Alternatively, you could be very heavy handed and just run something like 'pkill -9 *django*' before your django startup sequence.

Paul McMillan
+1  A: 

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 daemon property to True (see the docs -- it's the setDaemon method 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!-)

Alex Martelli
Thank you, Alex. I've since decided to just start a whole new non-django daemon for this, as it solves a whole set of complexity issues. I've thus lost the ability to try out your suggestion, I'm afraid, but I'll take your word for it and mark it as the answer. ;)
Brian M. Hunt