1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import ctypes
import inspect
import time
from threading import Thread

def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):
print(f'\nt -> {thread}')
print(f'\nthread.ident -> {thread.ident}')
_async_raise(thread.ident, SystemExit)
thread.join()

def func1():
while True:
try:
print(f'func1')
time.sleep(1)
except SystemExit:
print("!!!!")
sys.exit()
except:
print(traceback.format_exc())

i = Thread(target=func1, args=())
i.start()
time.sleep(3)
print(f'线程{i}的状态{i.is_alive()}, 线程{i}的名字{i.name}, 线程的方法{i.ident}')
print(type(i.name), i.name)
stop_thread(i)