How to force a thread to stop

Jean-Paul Calderone exarkun at divmod.com
Thu Jul 27 08:48:37 EDT 2006


On Thu, 27 Jul 2006 07:07:05 GMT, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
>On Wed, 26 Jul 2006 17:38:06 -0700, "Carl J. Van Arsdall"
><cvanarsdall at mvista.com> declaimed the following in comp.lang.python:
>
>> Well, I guess I'm thinking of an event driven mechanism, kinda like
>> setting up signal handlers.  I don't necessarily know how it works under
>> the hood, but I don't poll for a signal.  I setup a handler, when the
>> signal comes, if it comes, the handler gets thrown into action.  That's
>> what I'd be interesting in doing with threads.
>>
>	Well, first off, something in the run-time IS doing the equivalent
>of polling. When IT detects the condition of a registered event has
>taken place, it calls the registered handler as a normal subroutine.
>Now, that polling may seem transparent if it is tied to, say the OS I/O
>operations. This means that, if the process never performs any I/O, the
>"polling" of the events never happens. Basically, as part of the I/O
>operation, the OS checks for whatever data signals an event (some bit
>set in the process table, etc.) has happened and actively calls the
>registered handler. But that handler runs as a subroutine and returns.
>
>	How would this handler terminate a thread? It doesn't run /as/ the
>thread, it runs in the context of whatever invoked the I/O, and a return
>is made to that context after the handler finishes.
>
>	You are back to the original problem -- such an event handler, when
>called by the OS, could do nothing more than set some data item that is
>part of the thread, and return... The thread is STILL responsible for
>periodically testing the data item and exiting if it is set.
>
>	If your thread is waiting for one of those many os.system() calls to
>return, you need to find some way to kill the child process (which may
>be something running on the remote end, since you emphasize using SSH).
>

While you are correct that signals are not the solution to this problem,
the details of this post are mostly incorrect.

If a thread never performs any I/O operations, signal handlers will still
get invokes on the arrival of a signal.

Signal handlers have to run in some context, and that ends up being the
context of some thread.  A signal handler is perfectly capable of exiting
the thread in which it is running.  It is also perfectly capable of
terminating any subprocess that thread may be responsible for.

However, since sending signals to specific threads is difficult at best
and impossible at worst, combined with the fact that in Python you
/still/ cannot handle a signal until the interpreter is ready to let you
do so (a fact that seems to have been ignored in this thread repeatedly),
signals end up not being a solution to this problem.

Jean-Paul



More information about the Python-list mailing list