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

相关推荐
weixin_381288181 分钟前
Layui怎么在表格标题栏中嵌入一个迷你的HTML搜索表单
jvm·数据库·python
m0_747854524 分钟前
C# 文件系统Filter Hook C#能否在用户模式下拦截文件系统调用
jvm·数据库·python
嘻嘻哈哈樱桃7 分钟前
牛客经典101题题解集--二叉树
java·数据结构·python·算法·leetcode·职场和发展
cen__y9 分钟前
Linux05(管道)
linux·运维·服务器·c语言·开发语言·文件流
Frank学习路上10 分钟前
【Python】应用:发布pyproject.toml格式包到 PyPI
开发语言·chrome·python
奇妙之二进制14 分钟前
zmq源码分析之IO线程绑定时机
开发语言·网络
阿标的博客19 分钟前
Python学习(三):Python程序的运行方式
开发语言·python·学习
IMPYLH20 分钟前
Linux 的 split 命令
linux·运维·python·bash·运维开发·unix
0xDevNull21 分钟前
分布式事务实战指南:从理论到Seata落地
java·开发语言·后端
z44247532623 分钟前
MySQL如何配置自动清理失效事务锁_结合定时任务清理
jvm·数据库·python