Cancelling a python thread (revisited...)

Antoine Pitrou solipsis at pitrou.net
Mon Nov 9 07:20:44 EST 2009


Le Sun, 08 Nov 2009 21:04:06 -0800, John Nagle a écrit :
> Antoine Pitrou wrote:
>> John Nagle <nagle <at> animats.com> writes:
>>>     I'd argue against general thread cancellation.  Inter-thread
>>> signals, though, have safety problems no worse than the first-thread
>>> only signals we have now.  You're allowed to raise an exception in a
>>> signal handler, which is effectively thread cancellation.
>> 
>> Can you give an example of such "cancellation"? In any case, this would
>> be a side-effect of the current implementation, not officially
>> supported behaviour.
> 
>     It's not only documented behavior, it's an example in the official
> documentation.  See
> 
> 	http://docs.python.org/library/signal.html#example

Well, the only supported behaviour is to send signals to the main thread. 
Besides, it doesn't "cancel" the thread, it just raises an exception in 
it, which can be caught and silenced. Just try the following:


import signal, time

def handler(signum, frame):
    print 'Signal handler called with signal', signum
    raise IOError

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(2)

try:
    time.sleep(10)
except IOError:
    print "got IOError!"





More information about the Python-list mailing list