如果没有响应,如何设置线程的超时并终止线程?

时间:2016-10-09 13:13:06

标签: python multithreading

假设我们有一个如下代码示例,它会在5秒后打印hello, world。我想要一种方法来检查Timer线程是否超过5秒然后终止线程。

from threading import Timer
from time import sleep


def hello():
    sleep(50)
    print "hello, world"

t = Timer(5, hello)
# after 5 seconds, "hello, world" will be printed
t.start()

在上面的代码块hello中,处理时间超过5秒。

考虑hello函数,对外部服务器的调用不返回响应,甚至没有超时或任何异常!我想用sleep函数模拟问题。

1 个答案:

答案 0 :(得分:1)

您可以使用signal并调用其alarm方法。超时时间过后,将引发异常(您可以处理)。请参阅下面的(不完整)示例。

import signal

class TimeoutException (Exception):
    pass

def signalHandler (signum, frame):
    raise TimeoutException ()

timeout_duration = 5

signal.signal (signal.SIGALRM, signalHandler)
signal.alarm (timeout_duration)

try:
    """Do something that has a possibility of taking a lot of time 
    and exceed the timeout_duration"""
except TimeoutException as exc:
    "Notify your program that the timeout_duration has passed"
finally:
    #Clean out the alarm
    signal.alarm (0)

您可以在此处详细了解Python的signal https://docs.python.org/2/library/signal.html