I have a thread which every 10ms measures an voltage value (captured from an external device), applies some elementary low-pass filtering and stores the value in a variable lp_voltage. Every few seconds the main program needs to read the value stored in lp_voltage.
I have figured out two methods to possibly do that with the threading framework:
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.lp_voltage from time to time, and not to a full queue of data.What option is best? If queues are better, how to adapt them to my problem?
First method is OK if you know what you are doing.
More explanation:
In both method, you need to make sure your two threads have access to a shared variable(lp_voltage or v_queue). What the real advantage v_queue has is consistence. If you don't care about consistence, you can just simply use a variable.
To implement this more pythonic, you can wrap your whole project into an object. For example:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With