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

相关推荐
毋语天1 天前
Python 循环与列表详解:流程控制与核心数据结构
python
sparEE1 天前
c++字符串和自定义字面量
开发语言·c++
2401_850491651 天前
如何监控当前正在执行的SQL进程_SHOW PROCESSLIST
jvm·数据库·python
m0_702036531 天前
CSS如何优化浮动导致的布局渲染性能_清除浮动策略
jvm·数据库·python
m0_591364731 天前
golang如何实现语言包自动加载_golang语言包自动加载实现指南
jvm·数据库·python
麻雀飞吧1 天前
期货量化策略讲解:天勤量化下的跨期价差均值回归策略实战
python·算法·均值算法·回归
用户8356290780511 天前
使用 Python 处理 Word 文档书签
后端·python
dinglu1030DL1 天前
如何让水平滚动条始终固定在页面底部
jvm·数据库·python
2301_783848651 天前
Python Selenium怎么定位元素_By.XPATH与By.CSS_SELECTOR操作DOM节点
jvm·数据库·python
Li emily1 天前
用外汇实时api搭建多货币对波动率实时看板
python·api·fastapi