3

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:

What option is best? If queues are better, how to adapt them to my problem?

Sraw
  • 18,892
  • 11
  • 54
  • 87
Daniel Arteaga
  • 467
  • 3
  • 9

1 Answers1

3

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()
Sraw
  • 18,892
  • 11
  • 54
  • 87
  • I ended up using a solution like the one you propose, and it worked fine. The only difference is that took the main code I out of the class, and instead called read `lp_voltage` property of the `task` object. – Daniel Arteaga Oct 20 '17 at 14:30