菜鸟IT的博客 >> Python
测试开通多个子线程(多线程),然后强制关闭子线程 | 强制关闭多线程里的子线程
import threading
import time
import inspect
import ctypes
def test1():
for i in range(5):
print("子线程1:%s" % i)
time.sleep(5)
# 如果创建Thread时执行的函数,函数运行结束意味着 这个子线程结束...
def test2():
for i in range(5):
print("子线程2:%s" % i)
time.sleep(5)
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
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:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
# ————————————————————————————————————————————
if __name__ == '__main__':
# 在调用thread之前打印当前线程信息
print(threading.enumerate())
# 创建线程
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
# 查看线程数量
thread_num = len(threading.enumerate())
print("主线程:线程数量是%d" % thread_num)
# 输出所有线程名字
print(str(threading.enumerate()),type(threading.enumerate()))
# 杀掉所有子线程
for i in range(0,len(threading.enumerate())):
if i==0:
print("第1个是主线程,不能关:",str(threading.enumerate()[0]))
else:
print("开始关闭子线程:",str(threading.enumerate()[i]))
stop_thread(thread=threading.enumerate()[i])
time.sleep(6)
print("主线程:主线程结束")
菜鸟IT博客[2022.04.15-23:14] 访问:318