How to set timeout for thread in case of no response and terminate the thread?
<p>Let's say we have a code sample as below which prints <code>hello, world</code> after 5 seconds. I want a way to check if <code>Timer</code> thread took more than 5 seconds then terminate the thread.</p>

<pre><code>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()
</code></pre>

<p>In the above code block <code>hello</code> will take more than 5 seconds to process.</p>

<p>consider <code>hello</code> function, a call to outside server that returns no response and even no exception for timeout or anything! I wanted to simulate the issue with <code>sleep</code> function.</p>

<p>You can use <code>signal</code> and call its <code>alarm</code> method. An exception (which you can handle) will be raised after the timeout time has passed. See an (incomplete) example below. </p>

<pre><code>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)
</code></pre>

<p>You can read more about Python's <code>signal</code> here <a href="https://docs.python.org/2/library/signal.html" rel="nofollow">https://docs.python.org/2/library/signal.html</a>.</p>

python multithreading