Skip to content

Commit 857de96

Browse files
+ Error handling in graceful shutdown
1 parent 6f98f04 commit 857de96

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/thread/thread.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
Overflow_In = Any
3131

3232

33+
Threads: set['Thread'] = set()
3334
class Thread(threading.Thread):
3435
"""
3536
Wraps python's `threading.Thread` class
@@ -108,6 +109,9 @@ def _wrap_target(self, target: Callable[..., Data_Out]) -> Callable[..., Data_Ou
108109
def wrapper(*args: Any, **kwargs: Any) -> Any:
109110
self.status = 'Running'
110111

112+
global Threads
113+
Threads.add(self)
114+
111115
try:
112116
self.returned_value = target(*args, **kwargs)
113117
except Exception as e:
@@ -118,6 +122,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:
118122

119123
self.status = 'Invoking hooks'
120124
self._invoke_hooks()
125+
Threads.remove(self)
121126
self.status = 'Completed'
122127
return wrapper
123128

@@ -156,7 +161,7 @@ def global_trace(self, frame, event: str, arg) -> Optional[Callable]:
156161

157162
def local_trace(self, frame, event: str, arg):
158163
if self.status == 'Kill Scheduled' and event == 'line':
159-
print('KILLED ident:%s' % self.ident)
164+
print('KILLED ident: %s' % self.ident)
160165
self.status = 'Killed'
161166
raise SystemExit()
162167
return self.local_trace
@@ -524,9 +529,14 @@ def service_shutdown(signum, frame):
524529
print('\nCaught signal %d' % signum)
525530
print('Gracefully killing active threads')
526531

527-
for thread in threading.enumerate():
532+
for thread in Threads:
528533
if isinstance(thread, Thread):
529-
thread.kill()
534+
try:
535+
thread.kill()
536+
except (exceptions.ThreadNotRunningError, exceptions.ThreadNotInitializedError):
537+
pass
538+
except Exception as e:
539+
print('Failed to kill ident: %d' % thread.ident or 0)
530540
sys.exit(0)
531541

532542

0 commit comments

Comments
 (0)