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

2024-10-01 09:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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 is being mutated”错误。 另外,如何确保线程无限运行,但process_ticks不会从deque插入相同的数据两次


Tags: andthe数据indatabufferitthis
1条回答
网友
1楼 · 发布于 2024-10-01 09:17:10

当某个事物发生变异时,迭代通常是定义错误的。这正是在您的例子中发生的:t1t2对缓冲区进行迭代的同时对其进行变异

问题是迭代假设项目之间有很强的关系;突变可能会打破这种局面。具体地说,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特别适合这样:您可以在不同的端插入和弹出。 这样做还有一个额外的优点,即您永远不能两次获得相同的元素

相关问题 更多 >