How to kill a thread?
fuzzyman at gmail.com
Mon Jun 9 22:52:25 CEST 2008
On Jun 9, 9:20 pm, Rhamphoryncus <rha... at gmail.com> wrote:
> On Jun 9, 5:33 am, Antoon Pardon <apar... at forel.vub.ac.be> wrote:
> > On 2008-06-07, Rhamphoryncus <rha... at gmail.com> wrote:
> > > On Jun 6, 12:44 pm, The Pythonista <n... at this.time> wrote:
> > >> It's always been my understanding that you can't forcibly kill a thread
> > >> in Python (at least not in a portable way). The best you can do is
> > >> politely ask it to die, IIRC.
> > > Inherently, the best you can do in most languages is ask them politely
> > > to die. Otherwise you'll leave locks and various other datastructures
> > > in an inconvenient state, which is too complex to handle correctly.
> > > The exception is certain functional languages, which aren't capable of
> > > having threads and complex state in the same sense.
> > Well it would of course depend on what is considered asking politely?
> > If one thread could cause an exception being thrown in an other thread,
> > would this be considered a polite way to ask? Would it be considered
> > an acceptable way?
> The exception must not be raised until a point explicitly designed as
> safe is hit. Otherwise, any function that manipulates data you'll
> still use will potentially be buggered. Consider sys.stdout: codecs,
> buffering, lots to go wrong.
Java and .NET both have ways of killing threads. They both work by
raising a 'ThreadAbort' (or similar) exception in the target thread.
In early implementations they both suffered from a similar problem.
You could protect locks (etc) by having a finally block that would
release all resources as needed - but what happens if the thread abort
exception is raised *inside* the finally block?
Java responded by deprecating thread aborting. .NET responded by
ensuring that a thread abort exception would never be raised inside a
finally block - if that happened the exception would only be raised
once the code has left the finally block.
Aborting threads in .NET can be extremely useful. Politely asking a
thread to die is no good if the task the thread is executing is
extremely coarse grained - it may not be able to respond to the
request for some time. If your code is structured correctly
(performing a long running background calculation for example) then
you may *know* that you can kill it without problems, but Python has
no native API to do this.
More information about the Python-list