python主动杀死线程

简介

在一些项目中,为了防止影响主进程都会在执行一些耗时动作时采取多线程的方式,但是在开启线程后往往我们会需要快速的停止某个线程的动作,因此就需要进行强杀线程,下面将介绍两种杀死线程的方式。

直接强杀,通过底层c抛出异常来杀死线程

import ctypes, inspect, threading, time

def stop_thread(thread):
    """
    杀死线程
    :param thread:需要杀死的线程
    :returns None
    """
    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:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")
    _async_raise(thread.ident, SystemExit)

t = None

def run():
    global t
    print('run start ')
    count = 1
    while True:
        print('wait',count,'s')
        time.sleep(1)
        count += 1
        if count == 8:
            if t is not None:
                stop_thread(t)

t = threading.Thread(target=run)
t.start()
t.join()

使用flag的方式,使线程跳出

此处可以直接使用一个flag,但我用了线程的event来控制线程的停止,event里面自带一个flag,默认为false,当event.set时 flag会变为true,clear则会将flag变为false,通过is_set来获取flag,isSet已经废弃。

import threading, time

class MyThread(threading.Thread):

    event = threading.Event()

    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.count = 1
    
    def run(self):
        print('MyThread start')
        while True:
            print(f'wait {self.count}s')
            time.sleep(1)
            self.count += 1
            if self.event.is_set():
                break
        print('MyThread end')

t = MyThread(name='test')
t.start()
time.sleep(10)
t.event.set()
MyThread start
wait 1s
wait 2s
wait 3s
wait 4s
wait 5s
wait 6s
wait 7s
wait 8s
wait 9s
wait 10s
MyThread end
posted @   形同陌路love  阅读(456)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示