Killing a thread

Gordon McMillan gmcm at hypernet.com
Fri Aug 4 12:55:56 EDT 2000


pauljolly at my-deja.com wrote in <8mduck$a7o$1 at nnrp1.deja.com>:

>Thanks, but this does not kill the thread. I have tried this within the
>python shell.

You don't kill threads. You ask them to exit. If you did manage to kill a 
thread, you would likely screw up your entire process, because there's no 
clean up code to free resources or let go of locks etc.

Note that Java has deprecated killing threads; not just because of the 
above reasons, but also because it usually didn't work - if the thread was 
doing a blocking call, on most OSes it wouldn't die until it returned from 
the call.

>For example, I started a thread in which I used time.sleep(120). Then I
>used join(10) to see whether after ten seconds join would kill the
>sleep thread still running. Join waited the ten seconds (sleep() was
>still running as it is set to 120 seconds), I then checked to see which
>threads were still running, and one of them was the thread which runs
>the function sleep(). Hence join did not kill the thread at all.
>
>Seems to me, that this is a slight problem within Python. For example,
>no timeout mechanism is provided for urllib.urlopen() and the threading
>capabilities do not allow for a timeout mechanism either. Something
>that I am told, in a response to my post from another newsgroup member,
>is not set to change in future versions of python.

It's a shame that most of the net stuff in the Python lib is written using 
blocking sockets. Of course, if you rewrote them to use non-blocking 
sockets, you'd have to completely restructure them, so using them would 
look completely different. (Well, if you use stackless, you can write non-
blocking code that looks just like blocking code, but that's another 
story).

Tim O'Malley, I believe, recently posted a clever little module that hides 
the socket module inside a wrapper that does timeouts. But the easiest path 
is just to ignore those threads that don't respond quickly enough. They'll 
get cleaned up when your process exits. In the meantime, they're blocked, 
so all they're eating is some memory.

- Gordon





More information about the Python-list mailing list