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

相关推荐
newbiai几秒前
TikTok矩阵账号引流怎么解决效率低成本高?
python·线性代数·矩阵
Java面试题总结6 分钟前
Tube - Video Reactions
开发语言·前端·javascript
深蓝电商API12 分钟前
结构化数据提取:XPath vs CSS 选择器对比
爬虫·python
kylezhao201917 分钟前
C#中 Invoke、begininvoke、InvokeRequired的详细讲解和三者之间的区别
开发语言·c#
SCBAiotAigc18 分钟前
2026.2.25:conda与uv并存时,如何取消base激活
人工智能·python·conda·uv
wanderful_19 分钟前
Django 模拟支付功能开发:踩坑与闭环实现
后端·python·django
bubiyoushang88819 分钟前
基于遗传算法的LQR控制器最优设计算法
开发语言·算法·matlab
YouGIS顽石工坊22 分钟前
坐标转换服务私有化部署指南 - 源码与Docker两种方案
python·restful·docker镜像·python源码·pyproj·坐标转换服务·高斯克吕格投影
谢尔登23 分钟前
深入React19任务调度器Scheduler
开发语言·前端·javascript
hoiii18724 分钟前
MATLAB中LSSVM工具包及简单例程详解
开发语言·matlab