KeyboardInterrupt and threading

Paul McGuire ptmcg at
Sat Jan 3 19:59:03 CET 2004

"Ivan Nestlerode" <q2n8byu02 at> wrote in message
news:a6562e06.0401021352.65aac82b at
> Hello comp.lang.python,
> I am attempting to write a threaded program right now in Python
> (version 2.3 on Debian unstable) and the current behavior of
> KeyboardInterrupt is causing me grief. From the documentation of the
> thread module in Python 2.3.3:
> "Threads interact strangely with interrupts: the KeyboardInterrupt
> exception will be received by an arbitrary thread. (When the signal
> module is available, interrupts always go to the main thread.)"
Is the signal module not available to you?
> Any ideas (besides rewriting the sloppy library code) would be much
> appreciated.
> Thanks,
> -Ivan

Assuming you have access to the signal module:
1. Create a boolean that you can periodically test for in your thread code,
to see if you should keep processing.  This may be a global singleton, a
global boolean, or something, but it needs to be visible to both the main
thread and the threaded code.  You probably have some compute intensive
loops such as:
    while( prime_factors < 1e15 ):
    while( optimization != converged ):
or even just
    while( True ):

Change these to reference the "keep processing" flag.
    while( keep_processing and prime_factors < 1e15 ):
    while( keep_processing and optimization != converged ):
or even just
    while( keep_processing ):  # no need to 'and' with True

2. Create a signal handler to trap for SIGINT. In the signal handler, set
the "keep-processing" bit to False:

import signal

def discontinue_processing(signl, frme):
    global keep_processing
    keep_processing = False
    return 0

signal.signal( signal.SIGINT, discontinue_processing )

Now your main thread will get the ^C interrupt and clear the
"keep_processing" flag, which will eventually get picked up by your worker
thread the next time it tests for it.

-- Paul

More information about the Python-list mailing list