Stopping threads from the outside

Peter Hansen peter at engcorp.com
Sun Mar 24 19:45:26 EST 2002


holger at trillke.net wrote:
> 
> Mainly i want to be able to replace running agents
> (for the develop/deploy/test-cycle).

So can you write the environment and the threads such
that they can always detect a termination flag and cleanly
terminate themselves?  Or do the agent modules call 
directly into each other's namespaces in some ugly way,
never calling into the environment/framework at all?

> So basically one Agent-Thread may call into methods of another
> agent (not message-oriented, calls into the other modules
> in the same thread).

Your "agents" sound a lot more like they are just threads,
but maybe I don't see the distinction.  From the above 
description, I think you'll have other problems on your hands
than just terminating the threads.  You've got what appears
to be a very highly coupled system, and I suspect that
the fix to that can also fix your termination problem.

> The prescribed "ThreadInterruptException" could be generated by the
> python-interpreter working on this thread. Something like
> threading.interrupt(threading.Thread-instance) would signal the
> interpreter to generate an exception on the next possible occasion. Is
> this nonsense or a sensitive approach?

Actually, I'm not sure there's any good reason why one couldn't
instrument the interpreter to check a single flag in the current
thread and automatically raise such an exception if it is true.
This would in general by much cleaner than any other approach.
While you would run the risk of corrupting your application if
you terminated a thread at the wrong moment, it would at least
ensure that the thread was not blocked in an OS call at the 
time (since of course the interpreter would not be running 
instructions from that thread in that case).

This sounds like it would take only a few minutes for someone
familiar with the interpreter which, unfortunately, I am not.
Of course, I could be wrong...

The approach I suggested in my other reply would still work
nicely if you can ensure the threads call through an intermediary
instead of directly into each other.  You might also try 
a low-performance hack until you have time to implement the
modification in the interpreter :-), which would be to
stick a flag check into a routine inserted with sys.settrace().
Have that routine raise the exception if the flag is set for
the current thread...

-Peter



More information about the Python-list mailing list