question about ctrl-d and atexit with threads
rdmurray at bitdance.com
rdmurray at bitdance.com
Fri Mar 6 19:32:27 CET 2009
Darren Dale <dsdale24 at gmail.com> wrote:
>On Mar 5, 6:27 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
>> En Thu, 05 Mar 2009 15:26:18 -0200, Darren Dale <dsdal... at gmail.com>
>> > On Mar 5, 12:02ï¿½pm, s... at pobox.com wrote:
>> >> What happens if you simply call
>> >> my_thread.setDaemon(True)
>> >> (or in Python 2.6):
>> >> my_thread.daemon = True
>> >> ? That is the documented way to exit worker threads when you want the
>> >> application to exit. From the threading module docs:
>> >> "The entire Python program exits when no alive non-daemon threads
>> >> are left."
>> > Thank you Skip, that solves the problem. I'm still curious what the
>> > difference is between python's handling of sys.exit and EOF, but its
>> > academic at this point.
>> Some applications open a new window for each document they're handling.
>> When you close the last window, the application exits ("close" does an
>> implicit "quit"). Note that this does *not* happen when you close the
>> first, original document you opened, but when there are no more documents
>> open. The first document is not special in this regard.
>> Python threads work the same way; a thread may finish, but as long as
>> there are other threads alive, the process continues running. Only after
>> the last thread has finished, the application quits. The main thread *is*
>> special sometimes, but not in this aspect,
>> Setting daemon=True is like telling Python "I don't care about this
>> thread; don't wait for it if that's the only thing you have to do".
>> Calling sys.exit() is an explicit statement: "I want this program to
>> finish now" (or as soon as possible). It doesn't wait for the remaining
>> threads (unless you explicitely do so, like in your code).
>Right, I understand all that. I don't understand how calling sys.exit
>at the python command line is different from invoking ctrl-D. They
>should both trigger the same mechanism if they are advertised as
>equivalent mechanisms for exiting the interpreter, shouldnt they?
First, just to make sure we are on the same page, I assume you
understand that 'ctlr-D' at the python interpreter prompt is
completely equivalent to your example file that does not call
sys.exit before the end of the script file. That is, ctrl-D is
"end of file" for the 'script' you are creating at the
interactive interpreter prompt.
When Gabriel says "as long as there are other threads alive, the
process continues running", that is the key to your question.
The main thread has exited (either the interpreter or your main
script file) but another thread is still running (your child
thread), so Python keeps executing that thread. sys.exit is
_not_ called at the end of the "main" script file, but only after
all threads have exited.
Unless, that is, you call sys.exit explicitly, or set daemon = True.
More information about the Python-list