[Python-3000] improved threading in py3k
tomerfiliba at gmail.com
Fri Aug 4 17:36:40 CEST 2006
python's threading model seems too weak imo. i'm not talking about
the GIL and the fact threads run one at a time -- i'm talking about the
incompleteness of the API of thread module.
once a thread is created, there is no way to kill it *externally*. which
is a pity, since the thread must be "willing" to die, for example:
i_am_alive = True
i_am_alive = False
but of course you can't trust all threads work this way. moreover,
if the thread calls an internal function that blocks but doesn't check
i_am_alive, it will never exit. not to mention messing around with
the proposed solution is introducing thread.kill, for example:
>>> import time
>>> import thread
>>> thread.start_new_thread(time.sleep, (10,))
thread.kill() would raise the ThreadExit exception at the context of the
given thread, which, unless caught, causes the thread to exit silently.
if it is the last thread of the process, ThreadExit is equivalent to
another issue is sys.exit()/SystemExit -- suppose a thread wants to
cause the interpreter to exit. calling sys.exit in any thread but the main
one will simply kill the *calling* thread. the only way around it is calling
os.abort or os._exit(*)... but these functions do not perform cleanups.
i would suggest raising SystemExit at the context of any thread, when
the exception is not caught, will re-raise the exception at the context
of the main thread, where it can be re-caught or the interpreter would exit.
and of course, once the functionality of the thread module is extended,
the threading module must be extended to support it as well.
- - - -
(*) about os._exit -- how about introducing os.exit, which would serve
as the "nicer" version of os._exit? os.exit would kill the process in
the same way SystemExit kills it (performing cleanups and all).
in fact, the interpreter would just call os.exit() when catching SystemExit.
it would also allow you to ensure the interpreter is killed, as SystemExit
can be caught by external code against your will.
More information about the Python-3000