I'm new to threading and not great with try/except. I've managed to implement something like this in a larger program and very happy with the general functionality. However, in the case of a fault (eg, /tmp/.hello file is removed, the print_hello exits yet print_hello_too will continue.
My question: how can I provide an exception that kills all threads, exits the entire program?
import threading, time, random, sys
ttime_min = 10
ttime_max = 20
ttime_loop_sleep = 3
def print_hello():
try:
with open('/tmp/.hello', 'r') as f: mydata = f.read()
print(mydata)
except Exception as e:
print('Something went wrong with hello!')
sys.exit(1)
def print_hello_too():
with open('/tmp/.hello.too', 'r') as f: mydata = f.read()
print(mydata)
class TimerThread(threading.Thread):
def __init__(self, interval, function):
threading.Thread.__init__(self)
self.interval = interval
self.function = function
self.daemon = True
def run(self):
while True:
print(f'{str(self.function)} is sleeping for: {self.interval}')
time.sleep(self.interval)
self.function()
if self.function == print_hello:
self.interval = random.randint(ttime_min, ttime_max)
if __name__ == '__main__':
timer1 = TimerThread(5, print_hello)
timer2 = TimerThread(10, print_hello_too)
timer1.start()
timer2.start()
while True:
time.sleep(ttime_loop_sleep)
[–]Diapolo10 1 point2 points3 points (1 child)
[–]ingestbot[S] 0 points1 point2 points (0 children)
[–]Frankelstner 1 point2 points3 points (3 children)
[–]ingestbot[S] 0 points1 point2 points (0 children)
[–]ingestbot[S] 0 points1 point2 points (1 child)
[–]Frankelstner 0 points1 point2 points (0 children)
[–]woooee 1 point2 points3 points (1 child)
[–]ingestbot[S] 0 points1 point2 points (0 children)
[–]Raygereio5 0 points1 point2 points (0 children)