[Python-Dev] Thread questionlet

Tim Peters tim.one@home.com
Tue, 29 Jan 2002 15:29:41 -0500


[Christian Tismer]
> ...
> My question, which I could not easily answer by reading
> the source is:
> What happens when the main thread ends? Do all threads run
> until they are ready too, or are they just killed away?

You're walking near the edge of a very steep cliff.  There are jagged rocks
a kilometer below, so don't slip <wink>.

It varies by OS, and even by exactly how the main thread exits.  Reading OS
docs doesn't really help either, because the version of threads exposed by
the C libraries may differ from native OS facilities in subtle but crucial
ways.

> And if they are killed, are they just removed, or do
> they all get an exception for cleanup?

Can only be answered one platform at a time.  They're not going to get a
*Python*-level exception, no.  Here's a simple test program:

import thread
import time

def f(i):
    while 1:
        print "thread %d about to sleep" % i
        time.sleep(0.5)

for i in range(3):
    thread.start_new_thread(f, (i,))

time.sleep(3)
print "main is done"

and a typical run on Windows:

C:\Code\python\PCbuild>\python22\python.exe tdie.py
thread 0 about to sleep
thread 1 about to sleep
thread 2 about to sleep
thread 0 about to sleep
thread 1 about to sleep
thread 2 about to sleep
thread 0 about to sleep
thread 1 about to sleep
thread 2 about to sleep
thread 0 about to sleep
thread 1 about to sleep
thread 2 about to sleep
thread 1 about to sleep
thread 0 about to sleep
thread 2 about to sleep
thread 1 about to sleep
thread 0 about to sleep
thread 2 about to sleep
thread 1 about to sleep
main is done

C:\Code\python\PCbuild>

I expect much the same on Linux (all threads die, no exceptions raised).
But, IIRC, the threads would keep going on SGI despite that the main thread
is history.

> ...
> When a thread ends, it may contain several levels of other
> C calls which might need to finalize, so I thought of
> a special exception for this, but didn't find such.

Closing threads cleanly is the programmer's responsiblity across all OSes.
It can be very difficult.  Python doesn't really help (or hinder).
Microsoft helps in that DLLs can define a "call on thread detach" function
that's automatically called when a thread detaches from the DLL, but Python
doesn't exploit that.  The DLL hook may not get called even if it did,
depending on exactly how a thread detaches (the Big Hammer last-chance Win32
TerminateProcess/TerminateThread functions generally leave things a mess --
"TerminateThread is a dangerous function that should only be used in the
most extreme cases", etc).