guopengfa
发布于 2021-08-02 / 553 阅读 / 0 评论 / 0 点赞

退出线程

停止线程的代码示例

import time
from threading import Thread
import inspect
import ctypes

def te1():
    while True:
        print('te1')
        time.sleep(1)

def _async_raise(tid, exctype):
    """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")

def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

if __name__ == '__main__':
    thread1 = Thread(target=te1)  # 创建线程
    thread1.start()  # 开始线程
    time.sleep(5)
    stop_thread(thread1)  # 停止线程

评论