如何存储和访问来自 deque 的值,其中 deque 正在被另一个线程修改?



我的程序有两个线程 - 第一个线程用于以字典列表的形式接收数据,第二个线程用于将值存储在数据库中。

buffer = collections.deque(maxlen=10)
def process_ticks(bufferarg):
while True:
for i in bufferarg:
#code to insert data in a database
#this tread receives the data and dumps it into a deque with a specified length (so it can function as a circular buffer)
t1 = threading.Thread(target=socket.connect)
#this threads accesses the deque and processes the data
t2 = threading.Thread(target=process_ticks(buffer))
t1.start()
t2.start()

但是,当我运行代码时,我收到"deque正在被更改"错误。 另外,如何确保线程无限运行,但process_ticks不会两次插入来自 deque 的相同数据?

在某物发生突变时迭代某物通常是不明确的。这正是您的情况:t1改变缓冲区,同时t2迭代缓冲区。

问题在于,迭代假定项目之间存在很强的关系;突变可能会破坏这一点。具体而言,deque迭代器可能会在删除元素时保留该元素,从而使对下一个元素的引用无效。

一个简单的解决方案是不使用迭代,而是一次删除一个元素:

def process_ticks(bufferarg):
while True:
try:
# get and remove one item from the end of the deque
item = bufferarg.popleft()
except IndexError:
# no data in buffer, try again immediately or sleep a little
continue
else:
# do something with item

deque特别适合于此:您可以在不同的末端插入和弹出。 这有一个额外的优势,即您永远无法两次获得相同的元素。

相关内容

最新更新