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

时间:2019-04-16 18:12:29

标签: python multithreading

我正在使用以下示例安全地停止线程。但是,如果我不知道确切的线程正在运行,该如何停止所有当前正在运行的线程?

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的情况下同时杀死多个线程?

1 个答案:

答案 0 :(得分:0)

要安全地杀死线程,让它监听信号,它可以是内部变量或队列

在这里我们定义了一个名为“ 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()
相关问题