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

相关推荐
kkai人工智能24 分钟前
AI写作:从“废话”到“爆款”
开发语言·人工智能·ai·ai写作
lizz314 小时前
C++模板编程:从入门到精通
java·开发语言·c++
吴佳浩4 小时前
Python入门指南(五) - 为什么选择 FastAPI?
后端·python·fastapi
shoubepatien4 小时前
JAVA -- 05
java·开发语言
寰天柚子4 小时前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
沐知全栈开发5 小时前
Bootstrap 下拉菜单:设计与实现指南
开发语言
2503_928411565 小时前
项目中的一些问题(补充)
人工智能·python·tensorflow
Evand J5 小时前
【MATLAB例程】多锚点RSSI定位和基站选择方法,基于GDOP、基站距离等因素。以Wi-Fi定位为例,附下载链接
开发语言·matlab·定位·gdop·rssi
superman超哥5 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉
vv_Ⅸ5 小时前
打卡day42
python