安全地停止Python中所有正在运行的线程

2024-05-08 00:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的示例来安全地停止线程。但是,如果我不知道哪些线程正在运行,如何停止当前正在运行的所有线程呢?你知道吗

class exampleThread(threading.Thread): 
    def __init__(self, name): 
        threading.Thread.__init__(self) 
        self.name = name

    def run(self): 
        try: 
            print('this thread is running')
            sleep(10)

        finally: 
            print('example thread ended') 

    def get_id(self): 
        if hasattr(self, '_thread_id'): 
            return self._thread_id 
        for id, thread in threading._active.items(): 
            if thread is self: 
                return id
    def raise_exception(self): 
        thread_id = self.get_id() 
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 
              ctypes.py_object(SystemExit)) 
        if res > 1: 
            ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 
            print('Exception raise failure')


    example = exampleThread('example') 
    example.start()

现在我的线程正在运行。但是如何同时杀死多个线程,而不知道它们是否正在运行并且example是否已声明?你知道吗


Tags: nameselfidifinitisexampledef
1条回答
网友
1楼 · 发布于 2024-05-08 00:26:13

为了安全地终止线程,让它监听信号,它可以是内部变量或队列

这里我们定义了一个名为“kill()”的方法,如果需要终止线程,它会将变量“running”设置为False

import threading
from time import sleep

class exampleThread(threading.Thread): 
    def __init__(self, name): 
        threading.Thread.__init__(self) 
        self.name = name
        self.running=True

    def run(self): 
        try: 
            while self.running:  # watch for incoming kill signal
                print('this thread is running')
                sleep(1)

        finally: 
            print('example thread ended') 

    def kill(self):  # self kill safely
        self.running = False

    def get_id(self): 
        if hasattr(self, '_thread_id'): 
            return self._thread_id 
        for id, thread in threading._active.items(): 
            if thread is self: 
                return id
    def raise_exception(self): 
        thread_id = self.get_id() 
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 
              ctypes.py_object(SystemExit)) 
        if res > 1: 
            ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 
            print('Exception raise failure')


example = exampleThread('example') 
example.start()

sleep(2)
# alive = example.isAlive()

example.kill()

相关问题 更多 >