python多线程—终止子线程

总体思路

1、获取需要终止的子线程id
2、根据子线程id,终止子线程。

过程

  • 获取子线程id:
python 复制代码
import threading
Thread_id = threading.get_ident()  # 获取子线程的id值
  • 线程终止函数
python 复制代码
def async_raise(Thread_id, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(Thread_id)
    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")
  • 调用终止函数
python 复制代码
def stop_thread_func():
    async_raise(tid, SystemExit)

转自:https://blog.51cto.com/u_14224/6457768

相关推荐
T.Ree.17 小时前
汇编_读写内存
开发语言·汇编·c#
kaikaile199517 小时前
基于MATLAB的直接序列扩频(DSSS)通信系统仿真实现
开发语言·matlab
daqinzl17 小时前
Ubuntu 使用 Python 启动 HTTP 服务
python·ubuntu·http server 服务
czhc114007566318 小时前
C#1114 枚举
开发语言·c#
qunshankeji18 小时前
交通事故自动识别_YOLO11分割_DRB实现
python
z_鑫18 小时前
Java线程池原理深度解析
java·开发语言·后端
小呀小萝卜儿18 小时前
2025-11-14 学习记录--Python-特征归一化方法(Min-Max或StandardScaler)
开发语言·python·学习
顾安r18 小时前
11.14 脚本网页 青蛙过河
服务器·前端·python·游戏·html
测试199818 小时前
如何用Appium实现移动端UI自动化测试?
自动化测试·软件测试·python·测试工具·ui·职场和发展·appium
雪域迷影18 小时前
C++ 11 中的move赋值运算符
开发语言·c++·move