回答編集履歴
1
test
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
以下は `ctypes.pythonapi.PyThreadState_SetAsyncExc()` 使う方法です。
|
2
|
+
|
2
3
|
```python
|
3
4
|
import threading
|
4
5
|
import ctypes
|
@@ -18,6 +19,14 @@
|
|
18
19
|
except:
|
19
20
|
print('terminate loop2')
|
20
21
|
|
22
|
+
def terminate_threads(*threads):
|
23
|
+
for th in threads:
|
24
|
+
tid = [tid for tid, thr in threading._active.items() if thr is th]
|
25
|
+
if tid:
|
26
|
+
ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
27
|
+
ctypes.c_long(tid[0]), ctypes.py_object(ValueError))
|
28
|
+
th.join()
|
29
|
+
|
21
30
|
if __name__ == "__main__":
|
22
31
|
thread_1 = threading.Thread(target=loop_1)
|
23
32
|
thread_2 = threading.Thread(target=loop_2)
|
@@ -26,10 +35,5 @@
|
|
26
35
|
thread_2.start()
|
27
36
|
|
28
37
|
time.sleep(2)
|
29
|
-
|
38
|
+
terminate_threads(thread_1, thread_2)
|
30
|
-
tid = [tid for tid, thr in threading._active.items() if thr is th]
|
31
|
-
if tid:
|
32
|
-
ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
33
|
-
ctypes.c_long(tid[0]), ctypes.py_object(ValueError))
|
34
|
-
th.join()
|
35
39
|
```
|