473,785 Members | 2,289 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Timing out arbitrary functions

I have a problem and I don't know where to start looking for a solution.

I have a class that needs to call an arbitrary function and wait for a
result. The function, being completely arbitrary and not under my control,
may be very time consuming and possibly may not even halt. My class needs
to be able to give up waiting for a result after a specified amount of
time.

I'm thinking something conceptually like this:

# pseudo-code:
set time out to 30 seconds
try:
result = somefunction()
except TimeOut:
# 30 second time out happened
print "somefuncti on() timed out without returning"
else:
print "somefuncti on() returned %s" % result
The easy (for some definition of easy) solution would be to code
somefunction() so that it raised an exception if it hadn't returned a
result within a certain time. Unfortunately, I can't do rely on that -- I
only have control over the calling code, not the called somefunction(),
which may be any arbitrary function.

How do others handle something like this? What should I be looking for?
I'm after a lightweight solution, if any such thing exists.

Thanks,
--
Steven.

Dec 24 '05 #1
5 1454
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
How do others handle something like this? What should I be looking for?
I'm after a lightweight solution, if any such thing exists.


Is something stopping you from using sigalarm?
Dec 24 '05 #2
Steven D'Aprano wrote:
I have a problem and I don't know where to start looking for a solution.

I have a class that needs to call an arbitrary function and wait for a
result. The function, being completely arbitrary and not under my control,
may be very time consuming and possibly may not even halt. My class needs
to be able to give up waiting for a result after a specified amount of
time.

I'm thinking something conceptually like this:

# pseudo-code:
set time out to 30 seconds
try:
result = somefunction()
except TimeOut:
# 30 second time out happened
print "somefuncti on() timed out without returning"
else:
print "somefuncti on() returned %s" % result
The easy (for some definition of easy) solution would be to code
somefunction() so that it raised an exception if it hadn't returned a
result within a certain time. Unfortunately, I can't do rely on that -- I
only have control over the calling code, not the called somefunction(),
which may be any arbitrary function.

How do others handle something like this? What should I be looking for?
I'm after a lightweight solution, if any such thing exists.


For simple cases, I would use signal.alarm() with a SIGALARM handler
that raises a TimeOut exception. However, this is by no means
foolproof; you have to rely on the called function not to mess with
your signal handler. Plus, if your alarm occurs within a try-except
block that catches the TimeOut, it'll still be dropped. And to the best
of my knowledge, you can't otherwise forcibly terminate the execution
of a Python thread or block of code.

If you're going to be running untrusted code, I would use the
subprocess module to invoke a separate Python instance which takes the
code to be executed on stdin, and returns a pickled copy of the return
value on stdout. Then you can start it running, wait 30 seconds, and
then kill it if it hasn't already returned.

-- David

Dec 24 '05 #3
On Sat, 24 Dec 2005 04:47:34 -0800, Paul Rubin wrote:
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
How do others handle something like this? What should I be looking for?
I'm after a lightweight solution, if any such thing exists.


Is something stopping you from using sigalarm?


Pure ignorance of its existence.
Thanks, I'll check it out.
--
Steven.

Dec 24 '05 #4
Steven D'Aprano <st***@REMOVETH IScyber.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.
Dec 24 '05 #5
AOP would be a quite elegant way set timeouts for functions, in my
opinion. The nice thing in it is that, in principle, you can write a
single timeout advice code and then wrap it over any function you want
to timeout.

I wrote timeout_advice. py to demonstrate this a couple of years ago
(see http://www.cs.tut.fi/~ask/aspects/aspects.html). It may not
directly solve the problem at hand because it is thought to be used
with a wrap_around implementation that wraps methods in classes rather
than ordinary functions in modules. urllib.URLopene r.open is used as an
example in the code. Unfortunately, I still have not implemented the
wrapping for ordinary functions, although it should be straight-forward
with the same idea that is explained in the web page.

Of course, in the real life, timeouts are tricky and dangerous. The
consequences of interrupting a function that is not designed to be
interrupted, or leaving it running in the background after the timeout
(which is what timeout_advice. py does) may be surprising.

-- Antti Kervinen

Dec 28 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1472
by: cpptutor2000 | last post by:
Could some C++ guru please help me? I am using a BigInteger class which is really a wrapper around a C source file(mpi.c) that does arbitrary precision arithmetic operations. When I compile the C file using gcc -g -o mpi mpi.c rng.c -lm there are NO compilation or linking errors. However, when I try to compile the C++ wrapper class using g++ -g -o bigint bigint.C mpi.c rng.c -lm, I get strange linkage problems that all the functions in...
8
3193
by: Steve Neill | last post by:
Can anyone suggest how to create an arbitrary object at runtime WITHOUT using the deprecated eval() function. The eval() method works ok (see below), but is not ideal. function Client() { } Client.prototype.fullname = "John Smith"; var s = "Client"; eval("var o = new " + s + "();"); alert(o.fullname);
3
1827
by: Randy Yates | last post by:
Hi, We know we can build arrays of variables of the same type and arrays of functions of the same "type" (i.e., same return value and same parameters), but is there a way to automate the calling of a sequence of functions with arbitrary return types and/or parameters? -- Randy Yates Sony Ericsson Mobile Communications Research Triangle Park, NC, USA
2
3307
by: Steven D'Aprano | last post by:
The timeit module is ideal for measuring small code snippets; I want to measure large function objects. Because the timeit module takes the code snippet argument as a string, it is quite handy to use from the command line, but it is less convenient for timing large pieces of code or when working in the interactive interpreter. E.g. variations on this *don't* work: $ python Python 2.4.3 (#1, Jun 13 2006, 11:46:08)
1
1378
by: Gary Coutts | last post by:
Hi, I need to find out the execution time of some methods. Can anyone tell what the best resolution I can except when timing routine. I really need sub millisecond accuracy. Cheers
28
1609
by: walterbyrd | last post by:
Python seems to have a log of ways to do collections of arbitrary objects: lists, tuples, dictionaries. But what if I want a collection of non-arbitrary objects? A list of records, or something like that?
1
1708
by: MartyFromIreland | last post by:
Hi There! Run into a bit of a dilemma, I'm new to C# but I'm sure stacks of you will find this easy! Its regarding the timer functions, I've tried and failed numerous times as they just don't seem to do what it is I need to do! Here it goes: On my form I have 3 Labels: - Minutes (lbl_Minutes)
0
1947
by: Daniel Fetchinson | last post by:
On 4/15/08, Daniel Fetchinson <fetchinson@googlemail.comwrote: BTW, using the following ###################################################################### # CODE TO TEST BOTH FUNCTIONS back = fill_matrix(generate_zero())
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10357
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10101
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.