python强制停止线程学习

参考:

Python进阶之路 - Timeout | 超时中断 - 知乎 (zhihu.com)

写的很棒。

这里只记录我摘取的封装的一个class:

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ctypes
import threading


class ThreadKillOver(RuntimeError):
    """
    线程杀死后的反馈
    """
    def __init__(self):
        RuntimeError.__init__(self, "ThreadKillOver")

class ThreadKiller(threading.Thread):
    """separate thread to kill TerminableThread"""

    def __init__(self, target_thread, exception_cls, repeat_sec=2.0):
        threading.Thread.__init__(self)
        self.target_thread = target_thread
        self.exception_cls = exception_cls
        self.repeat_sec = repeat_sec
        self.daemon = True

    def run(self):
        """loop raising exception incase it's caught hopefully this breaks us far out"""
        while self.target_thread.is_alive():
            #ctypes.pythonapi.PyThreadState_SetAsyncExc是Python的ctypes库中的一个函数,
            # 用于设置Python线程的异步异常。这个函数的第一个参数是一个C语言中的线程状态对象,
            # 第二个参数是要抛出的异常。这个函数允许你在Python的C API层面控制线程的异常处理,
            # 通常情况下,你不需要直接使用这个函数,而是让Python的异常处理机制自动处理。
            ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.target_thread.ident),
                                                       ctypes.py_object(self.exception_cls))
            self.target_thread.join(self.repeat_sec)


class TerminableThread(threading.Thread):
    """a thread that can be stopped by forcing an exception in the execution context"""

    def terminate(self, exception_cls=ThreadKillOver, repeat_sec=1.0):
        """
        一个是exception_cls,这个的含义是,线程结束时会raise哪一种异常;
        另一个是repeat_sec,这个的含义是,杀手每隔多长时间去确认一次线程有没有死亡。
        如果repeat_sec为1,则线程杀手会每秒检查一次,如果线程还没死,就再杀一次,知道确认死亡为止。
        """
        if self.is_alive() is False:
            return True
        killer = ThreadKiller(self, exception_cls, repeat_sec=repeat_sec)
        killer.start()
相关推荐
lixora2 分钟前
银河麒麟高级服务器操作系统(ADM64 版)V10(SP1)搭建 Oracle 19c RAC
数据库
郝学胜-神的一滴6 分钟前
使用Linux的read和write系统函数操作文件
linux·服务器·开发语言·数据库·c++·程序人生·软件工程
kunge1v56 分钟前
学习爬虫第四天:多任务爬虫
爬虫·python·学习·beautifulsoup
萧鼎16 分钟前
Python schedule 库全解析:从任务调度到自动化执行的完整指南
网络·python·自动化
哲Zheᗜe༘19 分钟前
了解学习MySQL数据库基础
数据库·学习·mysql
Miqiuha40 分钟前
sql的表join怎么学?
数据库·sql
TiAmo zhang1 小时前
调查问卷管理系统开发 │ 系统功能概述
数据库·sqlserver
problc1 小时前
PostgreSQL pg_trgm中文模糊匹配优化技巧
数据库·postgresql
我真的是大笨蛋1 小时前
Redis的String详解
java·数据库·spring boot·redis·spring·缓存
lwprain1 小时前
图数据库neo4j desktop2.0初探
数据库·neo4j