Cancelling a python thread (revisited...)

Sven Marnach sven at pantoffel-wg.de
Sat Nov 7 21:04:04 EST 2009


Hi,

the Python threading module does not seem to provide a means to cancel
a running thread.  There are many discussions on the web dealing with
this issue and many solutions are offered, but none of them seems to
be applicable to my situation, which is as follows:

I have a C library which does some very computationally intensive
stuff.  Some functions in this library might run for a long time, and
the code in the library is optimized for speed.  The library is used
in C programs and also from a PyGTK GUI program.  In the GUI, you can
choose the computation parameters and than start the computation.  It
is run in a separate thread, which calls a function in the C library
via ctypes.

Now it should be possible to cancel the computation from the GUI.  In
the C programs, I can just kill or cancel the thread (there is no
cleanup to be done -- the thread does not use any system resources
apart from CPU time).  In Python, this is not possible.  The solutions
for this problem I found on the web usually recommend to have the
thread regularly check some variable and exit if this variable
indicates to do so.  This would have to be included in the C library
and would include quite a bit of code refactoring.  The check cannot
be included in the inner loop because it would lead to significant
performance loss.  Furthermore, I just do not want to mess up an
elegant and efficient library design which works perfect when used
from C just to make up for shortcomings in Python.

So do I really have to refactor my C library just because Python
Thread objects lack a cancel method?  Is there really no other way?
And why on earth doesn't that cancel method exist?  There *are* good
reasons to cancel a thread, just google for "terminate a Python
thread" for tons of examples.

I would be grateful for any suggestions.

Greetings from Germany and have a nice day,
    Sven



More information about the Python-list mailing list