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

相关推荐
清水白石00833 分钟前
Python 纯函数编程:从理念到实战的完整指南
开发语言·python
掘根37 分钟前
【C++STL】平衡二叉树(AVL树)
开发语言·数据结构·c++
twilight_46937 分钟前
机器学习与模式识别——机器学习中的搜索算法
人工智能·python·机器学习
叫我一声阿雷吧39 分钟前
JS实现响应式导航栏(移动端汉堡菜单)|适配多端+无缝交互【附完整源码】
开发语言·javascript·交互
前路不黑暗@1 小时前
Java项目:Java脚手架项目的文件服务(八)
java·开发语言·spring boot·学习·spring cloud·docker·maven
毅炼1 小时前
Java 集合常见问题总结(3)
java·开发语言·后端
沐知全栈开发1 小时前
ionic 对话框:深度解析与最佳实践
开发语言
Jia ming1 小时前
《智能法官软件项目》—罪名初判模块
python·教学·案例·智能法官
Jia ming2 小时前
《智能法官软件项目》—法律文书生成模块
python·教学·案例·智能法官软件