I often write multi threaded programs (mostly networking) and sometimes I run into a deadlock problem. This code fragment was very useful for me to detect such problems.

Usage:

import stacktracer stacktracer.trace_start("trace.html")

Then you will have a "trace.html" file showing the stack traces of all threads in your program. By default, the file is updated automatically in every 5 seconds. Whenever the program runs into a deadlock, cannot be terminated by Ctrl+C (or not responding to external network events, signals etc), I just wait 5 seconds, look at the HTML file and I can tell what it is waiting for.

It is especially useful to detect deadlocks because you can see which thread is waiting for what. If you detect a circle, you have a deadlock.