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

相关推荐
赖在沙发上的熊13 小时前
Python数据序列
开发语言·python
m0_3776182313 小时前
golang如何使用struct嵌套_golang struct结构体嵌套使用方法.txt
jvm·数据库·python
Hello--_--World13 小时前
Js面试题目录表
开发语言·javascript·ecmascript
聆风吟º13 小时前
【C标准库】深入理解C语言strcmp函数:字符串比较的核心用法
c语言·开发语言·库函数·strcmp
2301_8152795213 小时前
Redis如何降低快照对CPU的影响_合理分配RDB执行时机避开业务高峰期
jvm·数据库·python
Fanfanaas13 小时前
Linux 进程篇 (四)
linux·运维·服务器·开发语言·c++·学习
Sylvia-girl13 小时前
C++中类与对象
开发语言·c++
Greyson113 小时前
Go语言怎么用GitHub Actions_Go语言GitHub Actions教程【基础】.txt
jvm·数据库·python
qq_3422958213 小时前
CSS如何实现单选按钮自定义样式_利用伪元素隐藏默认UI
jvm·数据库·python
良木生香13 小时前
【C++初阶】:泛型编程的代表作---C++初阶模板
c语言·开发语言·数据结构·c++·算法