KeyboardInterrupt vs extension written in C

Diez B. Roggisch deets at nospam.web.de
Thu Oct 20 18:15:27 EDT 2005


Tamas Nepusz wrote:
> Hi everyone,
> 
> I have tried to do some googling before asking my question here, but I
> haven't found any suitable answer. I am developing a Python API for a
> graph library written in pure C. The library is doing an awful lot of
> math computations, and some of them can take a pretty long time
> (depending on the size of the input). If I invoke such calculation from
> Python using my own extension, the interpreter locks until the
> calculation is complete (I mean, it is not responding to Ctrl-C or
> SIGINT).
> 
> My question is: is there any way to allow the user to use Ctrl-C to
> generate a KeyboardInterrupt and cancel such large computations? I'm
> assuming that although pressing Ctrl-C may generate a KeyboardInterrupt
> in Python, it is not propagated to the user level until the call into
> the graph library returns. I tried to add Py_BEGIN_ALLOW_THREADS before
> the call to the underlying C library and Py_END_ALLOW_THREADS after
> returning from it, but I had no luck.

I'm not especially an expert with C-extensions. So I'm not sure if I can 
be of any help here. But if what you really are after is "only" 
terminating the whole program (instead of just the computation, and then 
continue), you might consider threads. Do the calls in a separate 
thread, and make that a daemon-thread. Then things _should_ work as 
expected, as the main thread will receive the signal. Hopefully... if 
your call releases the GIL. Which Py_*_ALLOW_THREADS seems to do. So - 
give it a try :)

Diez



More information about the Python-list mailing list