Search code examples
python-3.xmultithreadingubuntukill

Killing all processes and threads in python3.X


I'm writing a UI wrapper for reading some info using esptool.py

I have two active threads: UI and procesing - SerialReader. UI class has reference to the SerialReader and should stop SerialReader when it gets the exit command.

The problem is that I call esptool command which gets stuck in trying to read data over serial connection.

class SerialReaderProcess(threading.Thread):

    def __init__(self, window):
        super().__init__()
        self.window = window
        self.logger = window.logger
        self.window.set_thread(self)
        self._stop_event = threading.Event()

    def run(self):
        ...
        #read chip id
        esptool.main(['chip_id'])
        ...

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

What I want is to kill all active process of this program. When I call close the UI and call serialReaderProcess.stop() it doesn't stop the process. I can see the output of esptool on the console.

I don't care if I interrupt anything, no data can be corrupted.

I've tried sys.exit(0) to no avail. I've researched the problem but couldn't find a solution.

The OS is Ubuntu and I don't care about cross-platform features, but they would be nice


Solution

  • As stated in comments, setting the thread as Daemon solved the problem:

    super().__init__(daemon=True)
    

    Daemon threads are automatically killed when the program quits.

    More about daemons: Daemon Threads Explanation