在 Python 中使用类中的 threading.Event 终止线程

问题描述 投票:0回答:1

我有一个 Python 程序,它使用相当长的同步调用,因此事物被包装在线程中。这是一个粗略的 MVP:


class MyClass:
    processor = None

    def __init__(self):
        self.processor_active = threading.Event()
        self.processor_thread = threading.Thread(target=self.start_processing_thread, daemon=True)
        self.processor_thread.start()
        self.processor_active.wait()

    def start_processing_thread(self):
        self.processor = MyProcessor() # this line takes a while to run
        self.processor_active.set() # allows the constructor to release
        while self.processor_active.is_set():
            data = processor.process() # this line can take arbitrarily long to execute
            print(f"Received data: {data}")

    def shutdown(self):
        self.processor.shutdown() # to clean up resources
        self.processor_active.clear()
        self.processor_thread.join()

我的问题:在 MyClass 实例上调用 shutdown 会永远挂起而不会关闭,或者重复打印“已接收数据:”。看来我的线程无法获取线程事件的当前状态。我该如何解决它?

python python-multithreading
1个回答
0
投票

您的代码中似乎有一个拼写错误。 start_processing_thread 方法中应该使用 data = self.processor.process() ,而不是 data = process.process() 。如果没有 self 前缀,它会尝试访问名为processor的全局变量而不是实例变量self.processor。

这是代码的更正版本:

蟒蛇

导入螺纹

我的班级: 处理器=无

def __init__(self):
    self.processor_active = threading.Event()
    self.processor_thread = threading.Thread(target=self.start_processing_thread, daemon=True)
    self.processor_thread.start()
    self.processor_active.wait()

def start_processing_thread(self):
    self.processor = MyProcessor() # this line takes a while to run
    self.processor_active.set() # allows the constructor to release
    while self.processor_active.is_set():
        data = self.processor.process() # Corrected the variable name
        print(f"Received data: {data}")

def shutdown(self):
    self.processor.shutdown() # to clean up resources
    self.processor_active.clear()
    self.processor_thread.join()

定义 MyProcessor 类

MyProcessor 类: def 进程(自身): # 模拟处理 通过

def shutdown(self):
    # Clean up resources
    pass

通过此更正, shutdown 方法应该按预期工作,关闭 MyClass 实例并停止处理线程。

© www.soinside.com 2019 - 2024. All rights reserved.