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

相关推荐
sjmaysee2 分钟前
Java框架SpringBoot(一)
java·开发语言·spring boot
寒秋花开曾相惜5 分钟前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
想唱rap12 分钟前
Linux线程
java·linux·运维·服务器·开发语言·mysql
Tony Bai31 分钟前
Rust 看了流泪,AI 看了沉默:扒开 Go 泛型最让你抓狂的“残疾”类型推断
开发语言·人工智能·后端·golang·rust
njidf34 分钟前
C++与Qt图形开发
开发语言·c++·算法
qwehjk200840 分钟前
代码动态生成技术
开发语言·c++·算法
是翔仔呐43 分钟前
第11章 显示外设驱动:I2C协议OLED屏、SPI协议LCD屏字符/图片/中文显示
c语言·开发语言·stm32·单片机·嵌入式硬件·学习·gitee
jason成都1 小时前
IoT 设备监控系统实战:基于 EMQX 的 MQTT 连接监控与数据格式指纹识别
开发语言·python
铭毅天下1 小时前
EasySearch Rules 规则语法速查手册
开发语言·前端·javascript·ecmascript
YMWM_1 小时前
print(f“{s!r}“)解释
开发语言·r语言