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

相关推荐
techdashen4 分钟前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
少控科技11 分钟前
QT新手日记033
开发语言·qt
lixzest22 分钟前
PyTorch基础知识简述
人工智能·pytorch·python
飞Link27 分钟前
深度学习里程碑:ResNet(残差网络)从理论到实战全解析
人工智能·python·深度学习
王九思35 分钟前
Java 内存分析工具 MAT
java·开发语言·安全
superman超哥1 小时前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
夕除1 小时前
java--2
java·开发语言
ASS-ASH1 小时前
霸王色霸气的本质概括分析
人工智能·python·机器学习·大脑·脑电波
ValidationExpression1 小时前
学习:词嵌入(Word Embedding / Text Embedding)技术
python·学习·ai
星辰徐哥1 小时前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust