zoukankan      html  css  js  c++  java
  • killable thread的python实现

    python没有为内置的threading.Thread类提供一个kill接口,可以通过使用CPython API向线程抛出一个SystemExit异常来终止线程。如果线程没有被系统调用阻塞(sleep, recv, accept等),线程将会强制退出。参考连接:https://github.com/munshigroup/kthread.

    import ctypes
    import inspect
    
    try:
        import thread
    except ImportError:
        import _thread as thread
    import threading
    
    name = "kthread"
    
    def _async_raise(tid, exctype):
        if not inspect.isclass(exctype):
            raise TypeError("Only types can be raised (not instances)")
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("Invalid thread ID")
        elif res != 1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
            raise SystemError("PyThreadState_SetAsyncExc failed")
    
    class KThread(threading.Thread):
        def _get_my_tid(self):
            if not self.isAlive():
                raise threading.ThreadError("Thread is not active")
            
            if hasattr(self, "_thread_id"):
                return self._thread_id
    
            for tid, tobj in threading._active.items():
                if tobj is self:
                    self._thread_id = tid
                    return tid
            
            raise AssertionError("Could not determine the thread's ID")
        
        def raise_exc(self, exctype):
            _async_raise(self._get_my_tid(), exctype)
        
        def terminate(self):
            """cause the thread to exit silently (unless caught)"""
            # terminate会被系统调用(recv, sleep, accept等)阻塞
            self.raise_exc(SystemExit)
    
        def kill(self):
            self.terminate()
            
        def exit(self):
            self.terminate()
  • 相关阅读:
    构造函数的继承
    创建一个不被销毁的空间 闭包小应用
    如何在Linux上恢复误删除的文件或目录
    一文详解 Ansible 自动化运维
    Shell 脚本编程最佳实践
    10 分钟看懂 Docker 和 K8S!
    BGP路由协议详解(完整版)
    浅析 Linux 中的零拷贝技术
    2020年DevOps工程师入门指南
    一条更新的SQL如何执行
  • 原文地址:https://www.cnblogs.com/zcsh/p/14352765.html
Copyright © 2011-2022 走看看