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 分钟前
无中生有 之 从0开始写一个动态定时任务管理
java·开发语言
2501_901006479 分钟前
Golang怎么用gRPC Gateway_Golang gRPC Gateway教程【经典】
jvm·数据库·python
2501_9012005311 分钟前
golang如何实现错误预算Error Budget计算_golang错误预算Error Budget计算实现实战
jvm·数据库·python
2401_8676239822 分钟前
如何解决OUI图形界面无法调用_xhost与DISPLAY变量设置
jvm·数据库·python
Dxy123931021631 分钟前
Python 去除 HTML 标签获取纯文本
开发语言·python·html
2401_8246976638 分钟前
CSS如何实现元素反转特效_使用transform-scaleX(-1)操作
jvm·数据库·python
CLX05051 小时前
如何在 WordPress AMP 网站中为特定模板禁用 AMP 渲染
jvm·数据库·python
砚底藏山河1 小时前
python、JavaScript 、JAVA,定制化数据服务,助力业务高效落地
java·javascript·python
神明9311 小时前
如何实现SQL动态字段选择查询_利用反射或动态拼接字符串
jvm·数据库·python
洛的地理研学1 小时前
Python下载并处理MOD13A3植被指数数据
开发语言·python