'Python threading - Handling threads when main thread raises an exception

I have a thread that reads data from a data acquisition device. When my main function crashes, it doesn't kill the data acquisition thread. How can I stop the data acquisition if there's an exception outside the thread?

A simplified version of my program is:

class Daq_reader():
    def __init__(self):
        self.keepReading = True
        self.data = []

    def acquire(self):
        while self.keepReading:
            self.data = append_new_data(data)
            time.sleep(1)

def main():
    reader = Daq_reader()
    daq_thread = threading.Thread(target=reader.acquire, daemon=True)
    daq_thread.start()

    # rest of program here that might crash

I tried with daemon being True and False. Thank you!



Solution 1:[1]

it looks like you want to kill your thread. You can use python-worker (link) to create and abort the worker.

from worker import worker

class Daq_reader():
    def __init__(self):
        self.keepReading = True
        self.data = []

    @worker
    def acquire(self):
        while self.keepReading:
            self.data = append_new_data(data)
            time.sleep(1)

def main():
    try:
        reader = Daq_reader()
        reader_woker = reader.acquire()
    except:
        reader_woker.abort()

your reader.acquire() will be run in your background automatically when you decorate it with @worker

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danangjoyoo