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

相关推荐
老师好,我是刘同学3 小时前
Python执行命令并保存输出到文件
python
啵啵鱼爱吃小猫咪5 小时前
机械臂阻抗控制github项目-mujoco仿真
开发语言·人工智能·python·机器人
似水明俊德5 小时前
02-C#
开发语言·c#
MaximusCoder5 小时前
等保测评命令——Centos Linux
linux·运维·经验分享·python·安全·centos
yunyun321235 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
m0_662577975 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
oem1105 小时前
C++中的享元模式实战
开发语言·c++·算法
songyuc6 小时前
【PyTorch】感觉`CrossEntropyLoss`和`BCELoss`很类似,为什么它们接收labels的shape常常不一样呢?
人工智能·pytorch·python
似水明俊德6 小时前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
ℳ๓₯㎕.空城旧梦6 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python