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

相关推荐
Sylvia-girl2 小时前
Java——抽象类
java·开发语言
Yana.nice4 小时前
Bash函数详解
开发语言·chrome·bash
江沉晚呤时5 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
电脑能手5 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
tomorrow.hello6 小时前
Java并发测试工具
java·开发语言·测试工具
Edward-tan6 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
晓13136 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊6 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
倔强青铜三6 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三7 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试