I'm rather new to Python and I'm trying to solve a small problem with Threads. This might be "oh that's easy, it's simple_method()", or it could be a "sorry, that's totally impossible", I'm not sure.
I know that killing a thread externally is impossible, but that's not what I want to do here. What I have is a thread that has to stop itself, without having to reach the end of the run() method. Specifically, what I have is a thread that needs to complete all its work within a given amount of time, or else timeout with some special timeout-handling code if it can't:
So run() runs the thread's normal code, and timeout() is the out-of-time code. The thing is, if timeout() runs, the thread needs to go away when that method is done, it cannot go back to run() and keep executing code, and just blocking forever isn't great either (lots of these threads will be created). Without a goto to the end of my run() method, how can I accomplish this? Or, do I need to rethink my solution entirely and not rely on a Timer started when the thread is?
Thanks.
I know that killing a thread externally is impossible, but that's not what I want to do here. What I have is a thread that has to stop itself, without having to reach the end of the run() method. Specifically, what I have is a thread that needs to complete all its work within a given amount of time, or else timeout with some special timeout-handling code if it can't:
Code:
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.timer = Timer(5.0, self.timeout)
def run(self):
self.timer.start()
# ... do stuff ....
def timeout(self):
# timeout code
# End of timeout code - thread has done internal cleanup and it's perfectly acceptable to kill it here
Thanks.