Skip to content

Commit 0af38c4

Browse files
committed
Kill all new threads.
1 parent 3912c81 commit 0af38c4

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

dash/testing/application_runners.py

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -102,24 +102,27 @@ def tmp_app_path(self):
102102
return self._tmp_app_path
103103

104104

105-
class StoppableThread(threading.Thread):
106-
def get_id(self): # pylint: disable=R1710
107-
if hasattr(self, "_thread_id"):
108-
return self._thread_id
109-
for thread_id, thread in threading._active.items(): # pylint: disable=W0212
110-
if thread is self:
111-
return thread_id
105+
class KillerThread(threading.Thread):
106+
def __init__(self, **kwargs):
107+
super().__init__(**kwargs)
108+
self._old_threads = list(threading._active.keys()) # pylint: disable=W0212
112109

113110
def kill(self):
114-
thread_id = self.get_id()
115-
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
116-
ctypes.c_long(thread_id), ctypes.py_object(SystemExit)
117-
)
118-
if res == 0:
119-
raise ValueError(f"Invalid thread id: {thread_id}")
120-
if res > 1:
121-
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), None)
122-
raise SystemExit("Stopping thread failure")
111+
# Kill all the new threads.
112+
for thread_id in threading._active: # pylint: disable=W0212
113+
if thread_id in self._old_threads:
114+
continue
115+
116+
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
117+
ctypes.c_long(thread_id), ctypes.py_object(SystemExit)
118+
)
119+
if res == 0:
120+
raise ValueError(f"Invalid thread id: {thread_id}")
121+
if res > 1:
122+
ctypes.pythonapi.PyThreadState_SetAsyncExc(
123+
ctypes.c_long(thread_id), None
124+
)
125+
raise SystemExit("Stopping thread failure")
123126

124127

125128
class ThreadedRunner(BaseDashRunner):
@@ -154,7 +157,7 @@ def run():
154157
except SystemExit:
155158
logger.info("Server stopped")
156159

157-
self.thread = StoppableThread(target=run)
160+
self.thread = KillerThread(target=run)
158161
self.thread.daemon = True
159162
try:
160163
self.thread.start()

0 commit comments

Comments
 (0)