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

相关推荐
集成显卡3 小时前
Rust实战七 |基于带 colored 颜色文字控制台的批量文件删除工具
开发语言·后端·rust
lifloveyou4 小时前
table接口结构
python
比昨天多敲两行4 小时前
linux 线程概念与控制
java·开发语言·jvm
huaweichenai4 小时前
php 根据每个类型的抽签范围实现抽签功能
开发语言·php
codeejun6 小时前
每日一Go-73、云原生成本优化 —— 资源限制 & 指标驱动扩容
开发语言·云原生·golang
Warson_L6 小时前
class 扩展
python
就叫_这个吧6 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解
Sam_Deep_Thinking6 小时前
聊聊Java中的of
java·开发语言·架构
前端与小赵7 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步20157 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频