threading: how to kill a (possibly blocked) thread?

Donn Cave donn at u.washington.edu
Wed Jan 17 13:06:51 EST 2001


Quoth rturpin at my-deja.com:
| In article <u1yu2vmiq.fsf at ctwd0143.fitlinxx.com>,
|   David Bolen <db3l at fitlinxx.com> wrote:
|> What you really need to do is ensure that your threads
|> can accept an external request to terminate themselves ..
|
| The ideal way to do this is with a timed interrupt that
| invokes a function in the thread. The thread would start
| by setting this interrupt:
|
|   set_interrupt(8, funcCallBack)
|
| Then, funcCallBack gets invoked every 8 seconds,
| interrupting what the thread is doing, and returning
| to the interrupted code when the function returns.
| Unfortunately, I don't see such a facility in the
| library.
|
|> .. The main thread code should then check the event
|> object periodically and exit nicely if it is set.
|
| Except for certain kinds of processing, such as FSMs,
| this gets REAL ugly REAL fast. It also fails to protect
| against the very things for which you want a guard,
| i.e., external events that never occur.

For me, thread dispatch from an event loop is really the only
way to go in a seriously multi-threaded system.  I do my
multithreaded programs on BeOS, where that event loop concept
is built into an OOP user interface system, and just about
anything is a thread.  (I'm writing this in a Python newsreader
where I count 14 threads at the moment, most of them waiting
patiently for a message in their event loop queue - mostly
windows, and a couple of network clients.)

It is far from ugly, really somewhat elegant.  Can't imagine
doing it any other way.

I would guess the reason you don't see an interrupt feature
would be that there is nothing portable in that department,
and if there were, it would probably be a pain to integrate
into Python.  One general portability problem is that the
interrupt will often cost you the blocking I/O that was
interrupted;  then you have to trap the exception raised by
the interrupted I/O call, and post the I/O again.

I take no position on killing threads, in principal, but
since you can't do it from Python anyway, threads have to
be more cooperative, and the stuff that happens has to be
better understood and accounted for.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list