Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read value from one thread in Python: queue or global variable?

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:

  • 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, which looks more pythonic. However I don't know how to adapt it for my problem: the main program only needs to access to the instantaneous value of the 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?

like image 354
Daniel Arteaga Avatar asked May 17 '26 22:05

Daniel Arteaga


1 Answers

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()
like image 153
Sraw Avatar answered May 19 '26 10:05

Sraw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!