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

相关推荐
2301_765703142 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708052 小时前
实时数据压缩库
开发语言·c++·算法
Hgfdsaqwr3 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
lly2024063 小时前
jQuery Mobile 表格
开发语言
一晌小贪欢3 小时前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模3 小时前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
惊讶的猫3 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
Halo_tjn3 小时前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr4 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448914 小时前
export_onnx.py_0130
pytorch·python·深度学习