zoukankan      html  css  js  c++  java
  • python中强制杀死线程

    python比较多的是用使用退出标记,让线程自己退出

     有时候有这样的需要,在某种情况下,需要在主线程中杀死之前创建的某个线程,可以使用下面的方法,通过调用python内置API,在线程中抛出异常,使线程退出。

    import threading
    import time
    import inspect
    import ctypes
    
    
    def _async_raise(tid, exctype):
        """Raises an exception in the threads with id tid"""
        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:
            # """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")
    
    
    def stop_thread(thread):
        _async_raise(thread.ident, SystemExit)
    
    
    class TestThread(threading.Thread):
        def run(self):
            print("begin run the child thread")
            while True:
                print("sleep 1s")
                time.sleep(1)
    
    
    if __name__ == "__main__":
        print("begin run main thread")
        t = TestThread()
        t.start()
        time.sleep(3)
        stop_thread(t)
        print("main thread end")

    这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。

    暗夜之中,才见繁星;危机之下,暗藏转机;事在人为,为者常成。
  • 相关阅读:
    Riverside Curio
    bzoj1010 [HNOI2008]玩具装箱toy
    bzoj1898 [Zjoi2005]Swamp 沼泽鳄鱼
    hdu 5435 A serious math problem
    poj2411 Mondriaan's Dream
    bzoj3450 Tyvj1952 Easy
    关于欧拉函数与莫比乌斯函数等一系列积性函数的线性筛
    NOIP后一波总结
    回忆一下电子科技大学春令营
    【算法】背包九讲
  • 原文地址:https://www.cnblogs.com/zenghansen/p/14969458.html
Copyright © 2011-2022 走看看