Check if a python thread threw an exception
I have a set of tasks to do in parallel, but at the end of them, I need to
know if any of the threads threw an exception. I don't need to handle the
exception directly, I just need to know if one of the threads failed with
an exception, so I can cleanly terminate the script
Here is a simple example:
#!/usr/bin/python
from time import sleep
from threading import Thread
def func(a):
for i in range(0,5):
print a
sleep(1)
def func_ex():
sleep(2)
raise Exception("Blah")
x = [Thread(target=func, args=("T1",)), Thread(target=func, args=("T2",)),
Thread(target=func_ex, args=())]
print "Starting"
for t in x:
t.start()
print "Joining"
for t in x:
t.join()
print "End"
Before "End", I want to iterate through the threads, see if any failed,
and then decide if I can continue with the script, or if I need to exit at
this point.
I don't need to intercept the exception or stop the other threads, I just
need to know at the end if any failed.
No comments:
Post a Comment