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

相关推荐
lntu_ling3 小时前
Python-基于Haversine公式计算两点距离
开发语言·python·gis算法
ShineWinsu8 小时前
对于C++:继承的解析—上
开发语言·数据结构·c++·算法·面试·笔试·继承
小付同学呀8 小时前
C语言学习(五)——输入/输出
c语言·开发语言·学习
梦幻精灵_cq9 小时前
学C之路:不可或缺的main()主函数框架(Learn-C 1st)
c语言·开发语言
哈里谢顿9 小时前
Django 应用 OOM(Out of Memory)故障的定位思路和排查方法
python·django
消失的旧时光-19439 小时前
C++ 多线程与并发系统取向(二)—— 资源保护:std::mutex 与 RAII(类比 Java synchronized)
java·开发语言·c++·并发
甄心爱学习9 小时前
【python】获取所有长度为 k 的二进制字符串
python·算法
福大大架构师每日一题10 小时前
go-zero v1.10.0发布!全面支持Go 1.23、MCP SDK迁移、性能与稳定性双提升
开发语言·后端·golang
tuotali202610 小时前
氢气压缩机技术规范亲测案例分享
人工智能·python
嫂子的姐夫10 小时前
030-扣代码:湖北图书馆登录
爬虫·python·逆向