I am writing a python program, In main function I am starting a thread which runs continuously. After starting the the thread the main function enters a while loop where it takes user input continuously. If there is a exception in child thread I want to end the main function also. What is the best way to do that?
Thanks in advance
Having a thread "controlling" its parent is not a good practice. It makes more sense for the main thread to manage/monitor/control the threads it starts.
So my suggestion is that your main thread starts 2 threads: the one you already have, which at some point finishes/raises an exception, and one reading user input. The main thread now waits (joins) for the former to finish, and exits once done.
from threading import Thread
import time
class ThreadA(Thread):
def run(self):
print 'T1: sleeping...'
time.sleep(4)
print 'T1: raising...'
raise RuntimeError('bye')
class ThreadB(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def run(self):
while True:
x = raw_input('T2: enter some input: ')
print 'GOT:', x
t1 = ThreadA()
t2 = ThreadB()
t1.start()
t2.start()
t1.join() # wait for t1 to finish/raise
print 'done'
Since ThreadB is daemonic, we don't have to explicitly make it stop, nor to join it. When the main thread exits, it exits as well.
IMO, there's no need to resort to low-level stuff like signals. This solution doesn't even require using try-except (though you may decide you want a try-except in ThreadA, to make it exit cleanly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With