Skip to main content
 首页 » 编程设计

python之如何在没有响应的情况下为线程设置超时并终止线程

2025年04月02日9dflying

假设我们有如下代码示例,它会在 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 函数模拟这个问题。

请您参考如下方法:

您可以使用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 .