一个强制退出线程的例子python

通过给线程里面抛异常来强制退出线程,以下程序为开启一个线程打印2秒的字符后强制线程结束

import serial
import threading
import time
import binascii
import struct
import ctypes
import inspect
def _async_raise(tid, exctype):
    # todo 强制退出线程  忽略掉报错
    try:
        """raises the exception, performs cleanup if needed"""
        tid = ctypes.c_long(tid)
        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")
    except:
        pass

def init_serial_thread(a):
    while True:
        print(a)

a = 120
t0 = threading.Thread(target=init_serial_thread, args=(a,))
t0.start()
time.sleep(2)
print("begin exit")
_async_raise(t0.ident, SystemExit)
t0.join()
print("exit")

Guess you like

Origin blog.csdn.net/weixin_43134049/article/details/120764789