Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multithreading - overwrite old value in queue?

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?

like image 589
user3692971 Avatar asked Dec 19 '22 04:12

user3692971


1 Answers

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.

like image 175
Snild Dolkow Avatar answered Dec 21 '22 17:12

Snild Dolkow