I have two threads: a producer and a consumer. The producer periodically acquires information and provides it to the consumer. The consumer wants only the most current copy of the information and will check it aperiodically and maybe a long intervals.
It seems like the simplest mechanism to facilitate this communication would be to create a Queue.Queue(maxsize=1)
. However, if the producer acquires new information before the old information is consumed it will block until the consumer uses the out of date information first. Is there a way for the producer to overwrite the old information?
Is there a better threadsafe mechanism to accomplish this?
The simplest fix would probably be to let the producer consume its old value, if there is one, before putting. You can use Queue.get_nowait()
for this.
Stylistically, I'm not too keen on using a Queue for something only ever intended to hold one object. A normal Lock + a reference variable will make it more obvious what the code does.
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