多线程 - 覆盖队列中的旧值? [英] multithreading - overwrite old value in queue?

查看:34
本文介绍了多线程 - 覆盖队列中的旧值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程:生产者和消费者.生产者定期获取信息并将其提供给消费者.消费者只想要信息的最新副本,并且会不定期地检查它,可能间隔很长时间.

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.

似乎促进这种通信的最简单机制是创建一个 Queue.Queue(maxsize=1).但是,如果生产者在旧信息被消费之前获取了新信息,它将阻塞,直到消费者首先使用过时的信息.生产者有没有办法覆盖旧信息?

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?

推荐答案

谢谢 Snild Dolkow.你的建议很有价值.在做进一步的研究时,我确实找到了一种似乎适用于我的特定情况的机制.A collections.deque([iterable[, maxlen]]) 将是线程安全的,在接受新数据时丢弃旧数据,并根据 文档:

Thank you Snild Dolkow. Your suggestions are valuable. In doing further research I did find a mechanism that seems intended for my particular situation. A collections.deque([iterable[, maxlen]]) would be thread-safe, discards old data when accepting new data, and according to the documentation:

它们也可用于跟踪交易和其他数据池只对最近的活动感兴趣.

They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

使用 maxlen=1 生产者将始终能够写入新数据.当消费者执行 pop() 时,它将始终获得最新的数据数据.如果 IndexError 被引发,表明双端队列为空,消费者将继续使用它上次收到的数据.

With a maxlen=1 the producer will always be able to write new data in. When the consumer does a pop(), it will always get the most recent data. If a IndexError is raised, indicating that the deque is empty, the consumer will continue to use the data it last received.

这篇关于多线程 - 覆盖队列中的旧值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆