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

相关推荐
sycmancia2 分钟前
Qt——Qt中的文件操作、文本流和数据流
开发语言·qt
吕源林3 分钟前
PHP源码能否在Chromebook上运行_ChromeOS硬件限制说明【解答】
jvm·数据库·python
pele4 分钟前
c++如何读取YAML格式配置文件_yaml-cpp库快速入门【详解】
jvm·数据库·python
Python大数据分析@6 分钟前
低代码爬虫工具结合Python Selenium,自动采集商品数据
爬虫·python·低代码
johnny2336 分钟前
Python生态GUI框架:Gooey、Pywinauto、PyQuery、JustPy、Maliang、
python
ACP广源盛139246256736 分钟前
长距传输全能芯 @ACP#GSV5800 Type‑C/DP1.4/HDMI2.0 高速延长芯片
c语言·开发语言·网络·人工智能·嵌入式硬件·计算机外设·电脑
好奇龙猫6 分钟前
[大学院-python-base gammer learning(1): setting conda + Jupyter ]
python·jupyter·conda
存在的五月雨8 分钟前
Python操作 调用yolov8n-pose
开发语言·python·yolo
weixin_580614008 分钟前
CSS如何处理颜色在不同浏览器的兼容性_利用特性查询适配色彩
jvm·数据库·python
2501_914245938 分钟前
Go语言如何遍历字符串_Go语言字符串遍历方法教程【指南】
jvm·数据库·python