atexit + threads = bug?

David Rushby DavidRushby at
Thu Jan 12 23:08:31 CET 2006

[Tim Peters]
> [David Rushby]
>> They say, "Functions thus registered are automatically executed upon
>> normal interpreter termination."  It seems like sophistry to argue that
>> "normal interpreter termination" has occurred when there are still
>> threads other than the main thread running.
> Well, since atexit callbacks are written in Python, it's absurd on the
> face of it to imagine that they run after the interpreter has torn
> itself down.

Of course.

> It's also strained to imagine that threads have nothing to do
> with shutdown...

I don't imagine that.

> You're welcome to suggest text you'd like better...

What I'd like is for the behavior to become less surprising, so that
the text could describe reasonable behavior, instead of retrofitting
the text to more clearly explain (what I regard as) flawed behavior.

What would be unreasonable about adding a
call before the call to
near the beginning of Py_Finalize?

Instead of _MainThread.__exitfunc having to rely on atexit.register to
ensure that it gets called, join_nondaemonic_threads would call
_MainThread.__exitfunc (or some functional equivalent).  Both
join_nondaemonic_threads and call_sys_exitfunc would execute while the
interpreter "is still entirely intact", as the Py_Finalize comment

The opening paragraph of the atexit docs could then read:
"The atexit module defines a single function to register cleanup
functions. Functions thus registered are automatically executed when
the main thread begins the process of tearing down the interpreter,
which occurs after all other non-daemonic threads have terminated and
the main thread has nothing but cleanup code left to execute."

This seems simple.  Am I overlooking something?

More information about the Python-list mailing list