0

Unlike this: Timeout on a function call

I'm trying to timeout a line of code within a thread (not the main thread).

Signal only works in main thread, so I can't use that.

The line I want to limit is a web request with the requests library:

s.get("https://www.google.com/")

I can't use requests built-in timeout, because it doesn't always time out under certain conditions.

User
  • 23,729
  • 38
  • 124
  • 207

1 Answers1

0

If you are using python's standard threading library, I don't think there is an easy way to terminate the thread once it has started. There are some options mentioned in this thread (:D), you could perhaps try. If you don't care when the thread completes and just want control back, you can provide timeout in join method. It would look like below,

th = threading.Thread(target=f)
th.start()    #starts thread
th.join(timeout=10) # you get control back in 10 seconds, but thread could still be running
if th.is_alive():
    print("still alive")

Other option (which I like) would be to use concurrent library,

from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result(timeout=10))    #within 10 seconds if result isn't returned you will get TimeoutError

Quoting from docs on result(timeout=None),

If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time

ranjith
  • 361
  • 4
  • 14