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

相关推荐
Wang's Blog1 分钟前
Java框架快速入门: Spring Security+OAuth2之多因子认证逻辑与实体类改造
java·开发语言·spring
传奇开心果编程5 分钟前
【Rust入门知识点学与练】第26课:Unsafe Rust
开发语言·学习·rust
bug总结5 分钟前
uniapp总结
开发语言·前端·javascript
zyeyeye9 分钟前
C++入门:从HelloWorld到命名空间揭秘
c语言·开发语言·c++·算法
励志不掉头发的内向程序员13 分钟前
【LibreCAD 2D架构】从 addHistory 到 RS_UndoCycle:LibreCAD 里的两套 History 与撤销机制
开发语言·c++·qt·学习·系统架构
Escalating_xu14 分钟前
【mmap 进程间通信】从共享内存到跨进程唤醒:用互斥锁、条件变量控制多个进程
java·linux·开发语言·jvm
走到天涯海角17 分钟前
pinia和Vuex的区别以及使用pinia
开发语言·前端·javascript
泡海椒19 分钟前
脚本包导入实战:JQuick-Java自定义包引入与别名配置教程
java·开发语言·python
fbbqt20 分钟前
Python模块与包
开发语言·python
数智化码农23 分钟前
半导体制造人力资源数字化选型:适配双用工体系,兼顾合规与人效
大数据·运维·python·制造