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")

 

這種方法是強制殺死線程,但是如果線程中涉及獲取釋放鎖,可能會導致死鎖。

更好的殺死線程的方式是使用退出標記,讓線程自己退出,具體可以看我的下一篇博客 : https://www.cnblogs.com/lucky-heng/p/11991695.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM