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

相关推荐
某人辛木4 分钟前
JDK安装配置
java·开发语言
fox_lht5 分钟前
第十章 通用集合
开发语言·后端·算法·rust
小王师傅667 分钟前
【Java结构化梳理】泛型-初步了解-下
java·开发语言
2601_9561394211 分钟前
文旅行业品牌全案公司哪家强
大数据·人工智能·python
hrhcode12 分钟前
【LangGraph】二.State 和 Node 的设计细节
python·ai·langchain·langgraph·ai框架
dfdfadffa21 分钟前
如何创建仅在首次订阅时执行一次计算的 RxJS 懒加载 Observable
jvm·数据库·python
SmartRadio23 分钟前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信 (采用Arduino代码框架)
开发语言·智能手机·esp32·长距离wifi
m0_6245785925 分钟前
SQL分组后如何计算移动平均值_利用窗口函数AVG配合ROWS
jvm·数据库·python