Stopping threads from the outside

Peter Hansen peter at engcorp.com
Sun Mar 24 17:37:57 EST 2002


holger at trillke.net wrote:
> 
> > > Peter Hansen wrote:
> > I'm curious what the agent actually does if it doesn't share
> > anything.  Does it not take input?  And produce output?
> > No opening files, accessing Queues and such?  If it does
> > any of those things, wouldn't that make it potentially a
> > problem if you killed it?
> 
> Well. my agents share a namespace (named share:-) through which they
> can get to one another.

So you can guarantee that the way they interact is through
carefully controlled interfaces which are still completely 
safe even in the face of asynchronous and unexpected thread
termination?

> You don't neccessarily need to brutally kill the thread without
> the running code in that thread to notice it. Something like this
> would be nice:
> 
> def run(self): # thread's run
>     try:
>         while something:
>             do_something()
>     except ThreadInterruptException,e:
>         niceley_free_locked_resources_or_such()

Well, if you're willing to do that, things become much easier,
perhaps.  It sounds like you have your threads talking together
or to a management thread in a controlled fashion, through 
the safe interfaces I mentioned above.  If that's the case, 
why not just have those low-level routines check for a thread
termination flag and "raise ThreadInterruptException" if
they see it?  Technically voluntary on the part of the thread,
but then it was supposed to be cooperating, right?

I've done this in one system by modifying 'threading' to
have a flag in each thread, and in several low-level 
routines I check for that flag and throw an exception
if I see it.  Threads have always executed cleanly and
cleaned up after themselves.  In the cases where threads
are actually blocking in operating system calls (reading
from serial ports, in my case), I contrived to make sure
they always have reasonably short timeouts (several seconds)
so they would always check for thread termination often
enough.  It all depends how much control you have over
the environment.

-Peter



More information about the Python-list mailing list