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

相关推荐
天天进步20151 分钟前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
aaPIXa6223 分钟前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
Ulyanov4 分钟前
雷达导引头体制演进、技术特点与数学模型
python·雷达电子对抗·导引头
eybk18 分钟前
写一个可以编制pdf文件的python程序
开发语言·python·pdf
卷无止境23 分钟前
从Python的cryptography库出发,从零开始理解密码学,到构建零信任网络
后端·python
YFJ_mily28 分钟前
**Python 实战:写一个论文 PDF 投稿自检工具|附 IPAT 2026 智能光子学会议征稿信息
人工智能·python·pdf·量子计算·论文投稿·智能光子学
三川69828 分钟前
Tkinter库的学习记录05-文本框Entry
python
cui_ruicheng33 分钟前
Python从入门到实战(八):封装、多态与抽象类
开发语言·python
apihz34 分钟前
台风实时与历史详情查询免费 API 接口完整教程
android·开发语言·tcp/ip·dubbo·台风·天气预报
知无不研1 小时前
c语言和c++中的静态关键字
开发语言·c++·静态关键字