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

相关推荐
CoderCodingNo12 分钟前
【GESP】C++一级真题 luogu-B4410 [GESP202509 一级] 金字塔
开发语言·c++
0思必得014 分钟前
[Web自动化] CSS基础概念和介绍
前端·css·python·自动化·html·web自动化
计算机徐师兄16 分钟前
Python基于Django的MOOC线上课程推荐数据分析与可视化系统(附源码,文档说明)
python·数据分析·django·慕课线上课程推荐·慕课线上课程推荐可视化系统·pytho线上课程推荐可视化·线上课程推荐数据分析可视化系统
free-elcmacom19 分钟前
Python实战项目<2>使用Graphviz绘制流程框图
开发语言·python·graphviz
ljuncong26 分钟前
python的装饰器怎么使用
开发语言·python
2501_9448755136 分钟前
Go后端工程师
开发语言·后端·golang
该用户已不存在39 分钟前
没有这7款工具,难怪你的Python这么慢
后端·python
听风吟丶42 分钟前
Java 反射机制深度解析:从原理到实战应用与性能优化
java·开发语言·性能优化
serve the people44 分钟前
tensorflow 零基础吃透:RaggedTensor 的不规则形状与广播机制 2
人工智能·python·tensorflow
Hello.Reader1 小时前
Flink ML 基本概念Table API、Stage、Pipeline 与 Graph
大数据·python·flink