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

相关推荐
qq_4017004115 分钟前
Qt 中文乱码的根源:QString::fromLocal8Bit 和 fromUtf8 区别在哪?
开发语言·qt
程序员敲代码吗1 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
EndingCoder1 小时前
案例研究:从 JavaScript 迁移到 TypeScript
开发语言·前端·javascript·性能优化·typescript
Yyyyy123jsjs1 小时前
如何通过免费的外汇API轻松获取实时汇率数据
开发语言·python
白露与泡影1 小时前
2026版Java架构师面试题及答案整理汇总
java·开发语言
喵手1 小时前
Python爬虫实战:GovDataMiner —— 开放数据门户数据集元数据采集器(附 CSV 导出)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·open data·开放数据门户数据集列表
历程里程碑2 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
一个天蝎座 白勺 程序猿2 小时前
KingbaseES查询逻辑优化深度解析:从子查询到语义优化的全链路实践
开发语言·数据库·kingbasees·金仓数据库
人工智能AI技术2 小时前
【Agent从入门到实践】43 接口封装:将Agent封装为API服务,供其他系统调用
人工智能·python