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

相关推荐
zhangyao9403301 小时前
关于js导入Excel时,Excel的(年/月/日)日期是五位数字的问题。以及对Excel日期存在的错误的分析和处理。
开发语言·javascript·excel
闲人编程1 小时前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
骑驴看星星a1 小时前
【Three.js--manual script】4.光照
android·开发语言·javascript
星释2 小时前
Rust 练习册 :Leap与日期计算
开发语言·后端·rust
悟能不能悟4 小时前
java的java.sql.Date和java.util.Date的区别,应该怎么使用
java·开发语言
Mr_Xuhhh4 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441334 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天4 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
Q_Q5110082854 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
_院长大人_5 小时前
设计模式-工厂模式
java·开发语言·设计模式