wierd threading behavior

Tim Peters tim.peters at gmail.com
Tue Oct 18 16:07:35 EDT 2005


[Qun Cao]
>> import thread
>> def main():
>>     thread.start_new(test.())
>>
>> def test():
>>     print 'hello'
>>
>> main()
>> "
>> this program doesn't print out 'hello' as it is supposed to do.
>> while if I change main()

[Neil Hodgson]
>    The program has exited before the thread has managed to run. It is
> undefined behaviour whether secondary threads survive main thread
> termination but it looks like they don't on your system.

In fact, they don't on most systems.

>    Use the threading module and call join to wait for all threads to
> complete before exiting the program.

That's a different story:  threads from the `thread` module have
entirely OS-specific behavior when Python shuts down.  Python knows a
lot more about threads from the newer `threading` module, & uses an
atexit() hook to ensure that the Python interpreter does _not_ go away
while a threading.Thread is still running(*).  IOW, Python does the
join() for you for threading.Thread threads -- there's no need to do
it yourself.

(*) Unless you explicitly mark it as a daemon thread.



More information about the Python-list mailing list