Cross-platform time out decorator

Chris Mellon arkanes at gmail.com
Thu Sep 27 16:40:16 EDT 2007


On 9/27/07, Hrvoje Niksic <hniksic at xemacs.org> wrote:
> Joel <joel.schaerer at gmail.com> writes:
>
> >> Note that, unlike the original alarm code, it doesn't really interrupt
> >> the timed-out method, it just returns the control back to the caller,
> >> using an exception to mark that a timeout occurred.  The "timed out"
> >> code is still merrily running in the background.  I don't know if it's
> >> a problem in your case, but it's an important drawback.
> >
> > There should be a method to stop the thread though?
>
> Not in Python.  Thread killing primitives differ between systems and
> are unsafe in general, so they're not exposed to the interpreter.  On
> Windows you can attempt to use ctypes to get to TerminateThread, but
> you'll need to hack at an uncomfortably low level and be prepared to
> deal with the consequences, such as memory leaks.  If the timeouts
> happen rarely and the code isn't under your control (so you have no
> recourse but to terminate the thread), it might be worth it though.
> --


You can use ctypes and the Python API to raise a Python exception in
the thread. I don't normally mention this, because it has some
limitations, but it results in essentially the same effect as the
signal based method. They both have the limitation that C code can't
be interrupted.



More information about the Python-list mailing list