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

相关推荐
一代明君Kevin学长3 分钟前
快速自定义一个带进度监控的文件资源类
java·前端·后端·python·文件上传·文件服务·文件流
martian66513 分钟前
深入解析C++驱动开发实战:优化高效稳定的驱动应用
开发语言·c++·驱动开发
HappRobot15 分钟前
python类和对象
开发语言·python
鸡吃丸子25 分钟前
React Native入门详解
开发语言·前端·javascript·react native·react.js
盼哥PyAI实验室28 分钟前
Python YAML配置管理:12306项目的灵活配置方案
开发语言·python
漂亮的小碎步丶29 分钟前
【启】Java中高级开发51天闭关冲刺计划(聚焦运营商/ToB领域)
java·开发语言
hd51cc37 分钟前
MFC运行时
开发语言·mfc
wniuniu_40 分钟前
ceph一些细节处理
开发语言·ceph
hd51cc40 分钟前
异常处理(Exception Handling)
开发语言
SadSunset42 分钟前
(19)Bean的循环依赖问题
java·开发语言·前端