Last active
November 17, 2022 15:01
-
-
Save bsphere/f1e0a7d033dab2871c5c to your computer and use it in GitHub Desktop.
How to catch exceptions raised by Python worker threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Queue | |
import threading | |
class WorkerThread(threading.Thread): | |
def __init__(self, q): | |
super(WorkerThread, self).__init__() | |
self q = q | |
self.exception = None | |
def run(): | |
try: | |
while not self.q.empty(): | |
item = None | |
try: | |
item = self.q.get(False) | |
# do your stuff | |
except Queue.Empty: | |
pass | |
finally: | |
if item: | |
self.q.task_done() | |
except Exception as e: | |
self.exception = e | |
def get_exception(): | |
return self.exception | |
class MyClass: | |
def spawn_threads(self, q): | |
self.threads = [] | |
for _ in range(NUM_THREADS): | |
t = WorkerThread(q) | |
self.threads,append(t) | |
t.start() | |
def raise_thread_exceptions(): | |
for t in self.threads: | |
e = t.get_exception() | |
if e: | |
raise e | |
def my_func(self): | |
q = Queue.Queue() | |
# do something and q.put() | |
self.spawn_threads(q) | |
q.join() | |
# raise exceptions from worker threads | |
self.raise_thread_exceptions() |
there's a bug here when all threads are thrown and the q still isn't empty.
L55 should be:
for t in threads: t.join()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
L8: self.q = q