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

相关推荐
额额额对了10 分钟前
嵌入式 Linux 启动程序文件
开发语言·嵌入式硬件·php
子非鱼a14 分钟前
【WEB】EasySSTI
java·开发语言·前端
奈葵20 分钟前
Python
开发语言·python
happylifetree28 分钟前
Python54-55:核心语法-数据容器-字典dict-案例
python
小小张说故事29 分钟前
Python 迭代器和生成器到底啥区别?3 个例子讲透,别再背概念了
python
Nebula_g35 分钟前
JavaSE项目实践:红包雨-线程池/线程
java·开发语言
外收内放36 分钟前
Python基础语法练习题(56优化版补充)
开发语言·python
小羊没烦恼!36 分钟前
jQuery1.5的改进细节
java·服务器·开发语言·前端·c#
程序员老陆1 小时前
C++ 未定义行为全景:对象模型、优化边界与工程防御
开发语言·c++·程序设计
嵌入式er1 小时前
影石系统组 一二面OC面经
java·开发语言