Timing out arbitrary functions

Paul Rubin http
Sat Dec 24 16:29:47 EST 2005


Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> > Is something stopping you from using sigalarm?
> 
> Pure ignorance of its existence.
> Thanks, I'll check it out.

Two things to keep in mind:

  - You can have only ONE alarm pending for the whole process.  If
different things in the program need timeouts of their own, you have
to manage that yourself, maybe with heapq.  And the thing you're
trying to time out may itself mess with the alarm or its handler.

 - The alarm raises an exception in the main thread.  If you want a
timeout in some other thread, you're more or less out of luck.  Antoon
Pardon has posted a couple times about a ctypes-dependent hack that
raises asynchronous exceptions in arbitrary threads, that might be
worth looking into if you have to.  I haven't done so for now.

Besides sigalarm you might be able to concoct something with SIGIO
(have another thread sleep til the timeout then send a character back
to the main process through a pipe) or some other signal (use
os.kill).  The same issues would apply as with sigalarm.



More information about the Python-list mailing list