Daniel Slater
Daniel Slater

Reputation: 4143

Make a blocking function timeout in Python

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

Upvotes: 2

Views: 805

Answers (1)

User
User

Reputation: 14873

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.

Upvotes: 2

Related Questions