using timers to force an execution time
nick at craig-wood.com
Thu Jul 16 15:29:59 CEST 2009
superpollo <user at example.net> wrote:
> Diez B. Roggisch wrote:
> > superpollo wrote:
> >>am i wrong?
> > No, you are right, for threads that is. You can try & trick around with the
> > trace-functionality of python, and some ctypes-based
> > system-thread-module-tricks that are, as mentioned before, black-magic & a
> > spinning gatling gun pointed to your very own lower extremities.
> > The only reliable way of terminating an asynchronous computation is to use
> > processes, since python2.6 that's rather convenient with the
> > multiprocessing-module. However, that imposes some limits to what you can
> > do.
> fair enough.
Or if you are on unix you can use signals...
It is probably just about acceptable to raise an exception in a signal
handler like this code does.
import signal, os, time
"""Thrown on alarm"""
def sig_alarm(signum, frame):
def time_out(t, fn, *args, **kwargs):
"""Calls fn with the args and kwargs returning its result or raising a TimeOut exception if it doesn't complete within t seconds"""
# Turn alarm off and read old value
old_alarm = signal.alarm(0)
# Install new handler remembering old
old_handler = signal.signal(signal.SIGALRM, sig_alarm)
# Set the timer going
rc = fn(*args, **kwargs)
# Restore the old handler
for repeat in range(10):
if __name__ == "__main__":
print "timed out"
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list