TimeOut in between threads

View: New views
1 Messages — Rating Filter:   Alert me  

TimeOut in between threads

by somnath chakrabarti :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi Python Tutor members,
 
I am learning the concept of threads in Python and trying to write a Python code that will start a thread (say t1) from main or any other thread and then t1 will call a certain function f1(). If the execution of function f1() takes more than a specified time (say 1000 secs), t1 will be canceled from the calling thread. The requirement is sort of implementing timeout using threads. I am writing using Python GUI (IDLE) in Windows and tried using the signal package but it didnot work in Windows.
 
Below is the code that I have written. Thread t calls timer thread p. But even after p is canceled, the function hello() keeps on printing 'Hello World' for sometime. Any idea of what I am missing or what is wrong? I feel like there should be more graceful solution for implementing timeouts in Python? Any help will be appreciated.
 
Here is my code -->
 
import threading
import time
"""Example of an implementation of threading.Thread
   with threading.Timer"""
global p
def onTimeout():
    p.cancel()
    print 'Time Exceeded.'
p = threading.Timer(5,onTimeout)
def hello():
    p.start()
    j = 0
    while j < 1000:
        if p.isAlive():
            print 'Hello World'
            j += 1
        else:
            break
    if p.isAlive():
        p.cancel()
   
class TestThread(threading.Thread):
    def __init__(self,group=None,target=None,name=None,args=(),kwargs={}):
        threading.Thread.__init__(self,group,target,name,args,kwargs)
       
global t
t = TestThread(None,hello,None,(),{})
start = time.time()
t.start()
end = time.time()
t.join()
print 'Time Taken: %1.3f' % (end-start)
print 'Back from Time Out.'
 
 
Here is result -->
 
Hello World
...
Hello World
Time Exceeded.Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Time Taken: 0.000
Back from Time Out.

--
Thanks and regards,
Somnath Chakrabarti.

_______________________________________________
Tutor maillist  -  Tutor@...
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor