从 Python 中的一个线程读取值:队列还是全局变量?
Read value from one thread in Python: queue or global variable?
我有一个线程,每 10 毫秒测量一个电压值(从外部设备捕获),应用一些基本的低通滤波并将该值存储在变量 lp_voltage
中。每隔几秒,主程序需要读取存储在 lp_voltage
.
中的值
我想出了两种方法可以使用 threading
框架来做到这一点:
- Sharing the global variable
lp_voltage
between the thread and the main program, using the global
keyword in the thread. This has the inconvenient of having to use global varialbles, which are often considered bad practice.
- Using the Queue module,看起来更 pythonic。但是我不知道如何针对我的问题调整它:主程序只需要不时访问
lp_voltage
的瞬时值,而不是完整的数据队列。
哪个选项最好?如果队列更好,如何使它们适应我的问题?
如果你知道自己在做什么,第一种方法就可以了。
更多说明:
在这两种方法中,您需要确保您的两个线程可以访问共享变量(lp_voltage
或 v_queue
)。 v_queue
真正的优势在于一致性。如果你不关心一致性,你可以简单地使用一个变量。
为了实现这个更 pythonic,您可以将整个项目包装到一个 object
中。例如:
class VoltageTask:
def __init__(self):
self.lp_voltage = 0
self.thread = Thread(target=self.update_voltage)
def update_voltage(self):
self.lp_voltage = your_function_to_get_voltage()
def main_thread(self):
...
def start(self):
self.thread.start()
self.main_thread()
if __name__ == "__main__":
task = VoltageTask()
task.start()
我有一个线程,每 10 毫秒测量一个电压值(从外部设备捕获),应用一些基本的低通滤波并将该值存储在变量 lp_voltage
中。每隔几秒,主程序需要读取存储在 lp_voltage
.
我想出了两种方法可以使用 threading
框架来做到这一点:
- Sharing the global variable
lp_voltage
between the thread and the main program, using theglobal
keyword in the thread. This has the inconvenient of having to use global varialbles, which are often considered bad practice. - Using the Queue module,看起来更 pythonic。但是我不知道如何针对我的问题调整它:主程序只需要不时访问
lp_voltage
的瞬时值,而不是完整的数据队列。
哪个选项最好?如果队列更好,如何使它们适应我的问题?
如果你知道自己在做什么,第一种方法就可以了。
更多说明:
在这两种方法中,您需要确保您的两个线程可以访问共享变量(lp_voltage
或 v_queue
)。 v_queue
真正的优势在于一致性。如果你不关心一致性,你可以简单地使用一个变量。
为了实现这个更 pythonic,您可以将整个项目包装到一个 object
中。例如:
class VoltageTask:
def __init__(self):
self.lp_voltage = 0
self.thread = Thread(target=self.update_voltage)
def update_voltage(self):
self.lp_voltage = your_function_to_get_voltage()
def main_thread(self):
...
def start(self):
self.thread.start()
self.main_thread()
if __name__ == "__main__":
task = VoltageTask()
task.start()