How to "kill" orphaned threads at program exit

Gabriel Genellina gagsl-py2 at
Mon Dec 29 05:33:19 CET 2008

En Sun, 28 Dec 2008 15:47:24 -0200, Roy Smith <roy at> escribió:

> In article
> <b133b978-fe63-4893-bb33-8c96bfb59522 at>,
>  "Giampaolo Rodola'" <gnewsg at> wrote:
>> I know that it's not possible to "kill" threads but I'm wondering if
>> does exist some workaround for my problem.
>> I have a test suite which does a massive usage of threads.
>> Sometimes happens that one test fails, the test suite keeps running
>> until the end, and when it's finished the program hangs on and the
>> only way to stop is to kill it manually.
> You don't say how you're creating your threads, so I'll assume you're  
> using
> threading.Thread().  After creating each thread, and before calling  
> start()
> on it, call setDaemon(True).

The hard part is, then, to figure out some condition for the non-daemon  
thread to wait for before exiting.
As a last resort -let's say, after waiting for N seconds for all threads  
to exit- one can use PyThreadState_SetAsyncExc to "inject" an exception  
into the unfinished threads. I think there is a recipe in the Python  
Cookbook for doing that using ctypes.

Gabriel Genellina

More information about the Python-list mailing list