Is there a way to tell if a thread has exited normally or because of an exception?
Asked
Active
Viewed 1.4k times
3 Answers
20
As mentioned, a wrapper around the Thread class could catch that state. Here's an example.
>>> from threading import Thread
>>> class MyThread(Thread):
def run(self):
try:
Thread.run(self)
except Exception as err:
self.err = err
pass # or raise err
else:
self.err = None
>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)
0
You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.
However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.

samoz
- 56,849
- 55
- 141
- 195
-
10 for success may be a pretty standard convention, but wouldn't a boolean `succeded` be a little easier on the meat interpreter? – Daren Thomas Jun 12 '09 at 13:38
-
It doesn't have to be global if I subclass Thread, just need a member variable in that to indicate success. I was just wondering if there is any builtin way to do this, like the process exit code. – Jiayao Yu Jun 12 '09 at 13:48
-
9Threads and global state. Two great tastes tthat tate gsrat eogetherrrrrrrrrrrrrrr Segmentation fault, core dumped. – Glyph Jun 15 '09 at 14:55
-
@Glyph note how I mentioned mutexs and semaphores though. – samoz Jun 15 '09 at 15:20
0
Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a try
...except
or try
...except
...else
block). Then the question just becomes "how to pass information from one thread to another", and I guess you already know how to do that.

user9876
- 10,954
- 6
- 44
- 66