Python 线程 - 当主线程引发异常时处理线程

发布于 2025-01-14 23:32:06 字数 552 浏览 5 评论 0原文

我有一个从数据采集设备读取数据的线程。当我的主函数崩溃时,它不会杀死数据采集线程。如果线程外出现异常,如何停止数据采集?

我的程序的简化版本是:

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

我尝试使用守护进程为 True 和 False。谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽容 2025-01-21 23:32:06

看起来你想杀死你的线程。您可以使用python-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()

当您使用 @worker 装饰时,您的 reader.acquire() 将自动在后台运行

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文