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

相关推荐
代码AI弗森2 分钟前
Git Bash 与 PowerShell:定位差异、使用场景与选择建议
开发语言·git·bash
青春不朽5124 分钟前
TensorFlow 入门指南
人工智能·python·tensorflow
bioinfomatic8 分钟前
对比学习基本原理——以DrugClip为例,从CLIP到DrugClip
人工智能·python
代码游侠14 分钟前
C语言核心概念复习(一)
c语言·开发语言·c++·笔记·学习
蜕变的土豆18 分钟前
grpc-通关速成
开发语言·c++
-To be number.wan19 分钟前
Python数据分析:英国电商销售数据实战
开发语言·python·数据分析
细节处有神明21 分钟前
开源数据之历史气象数据的获取与使用
人工智能·python·算法
xb113229 分钟前
C#生产者-消费者模式
开发语言·c#
小白开始进步29 分钟前
JAKA Zu12 机械臂运动学算法深度解析(含可视化方案)
python·算法·numpy
电商API&Tina30 分钟前
乐天平台 (Rakuten) 数据采集指南
大数据·开发语言·数据库·oracle·json