I have a python program that implements such threads:
class Mythread(threading.Thread): def __init__(self, name, q): threading.Thread.__init__(self) self.name = name self.q = q def run(self): print "Starting %s..." % (self.name) while True:
Call_threaded_program () is called from another program.
I have code that works under normal circumstances. However, if an error / exception occurs in one of the threads, then the program gets stuck (since the queuing is endlessly blocked). The only way to exit this program is to close the terminal itself.
What is the best way to end this program when the thread is up? Is there a way to do this differently? I know this question has been asked many times, but I still cannot find a convincing answer. I would really appreciate any help.
EDIT: I tried to remove the connection in the queue and used the global exit flag as suggested in Is there a way to kill Thread in Python? However, now the behavior is so strange that I can not understand what is happening.
import threading import Queue import time exit_flag = False class Mythread (threading.Thread): def __init__(self,name,q): threading.Thread.__init__(self) self.name = name self.q = q def run(self): try:
The program output is as follows:
#Threads get started correctly
Then the program simply freezes or continues to print active threads. However, since the exit flag is set to True, the thread start method is not executed. Therefore, I do not know how these threads are supported or what happens.
EDIT : I found a problem. In the above code, the method of receiving the stream was blocked and, therefore, could not complete the work. Using the get method with a timeout instead did the trick. I have code only for the launch method, which I changed below
def run(self): try: #Start Thread printing "Starting %s..."%(self.name) #Do Some processing while not exit_flag: try: data = self.q.get(True,self.timeout) print "%s processing %s"%(self.name,str(data)) self.q.task_done() except: print "Queue Empty or Timeout Occurred. Try Again for %s"%(self.name) # Exit thread print "Exiting %s..."%(self.name) except Exception as e: print "Exiting %s due to Error: %s"%(self.name,str(e))