2

I have a blocking function, sometimes it hangs indefinitly, it is not cpu bound, it's accessing something externaly also it's a call to unmanaged code. I would like this to work on Windows or Unix

What is the best practice for running this method with a timeout? I assume this will involve running a new thread and having a wait event. I'm after the most lightweight in terms of both lines of code and cpu.

Thanks

Daniel Slater
  • 4,123
  • 4
  • 28
  • 39
  • 4
    You will greatly increase your chances of getting an answer for your question if you include your input, what you have tried, your expected output vs. your actual output and the full stack trace of any errors you receive. You can also read [this guide](http://stackoverflow.com/help/mcve) – kylieCatt Jul 01 '15 at 12:44
  • 1
    This isn't for a specific case, it's a general question on best practice. – Daniel Slater Jul 01 '15 at 12:47
  • 2
    answers over there : http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish – lucasg Jul 01 '15 at 12:49
  • I think best practice would be to use the built-in tools unless your requirements made that solution inappropriate. – Peter Wood Jul 01 '15 at 12:53

1 Answers1

2

You would use the wait(timeout=None) method to wait with a timeout for results when you use a pool and asynchronous calls:

>>> import multiprocessing
>>> p = multiprocessing.Pool()
>>> a = p.apply_async(None) # Replace None with the function to execute.
>>> help(a.__class__)
Help on class ApplyResult in module multiprocessing.pool:

class ApplyResult(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self, cache, callback, error_callback)
 |  
 |  get(self, timeout=None)
 |  
 |  ready(self)
 |  
 |  successful(self)
 |  
 |  wait(self, timeout=None)
[...]

concurrent.futures also has wait methods or a timeout for get.

User
  • 14,131
  • 2
  • 40
  • 59