Is there a way to tell if a thread has exited normally or because of an exception?
In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.
You can't actually stop and then restart a thread since you can't call its start() method again after its run() method has terminated. However you can make one pause and then later resume its execution by using a threading. Condition variable to avoid concurrency problems when checking or changing its running state.
You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.
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',)
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