我的程序有两个线程-第一个线程用于接收字典列表形式的数据,第二个线程用于将值存储在数据库中
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插入相同的数据两次
当某个事物发生变异时,迭代通常是定义错误的。这正是在您的例子中发生的:
t1
在t2
对缓冲区进行迭代的同时对其进行变异问题是迭代假设项目之间有很强的关系;突变可能会打破这种局面。具体地说,
deque
迭代器可以在删除元素时保存该元素,从而使对下一个元素的引用无效一个简单的解决方案不是使用迭代,而是一次删除一个元素:
deque
特别适合这样:您可以在不同的端插入和弹出。 这样做还有一个额外的优点,即您永远不能两次获得相同的元素相关问题 更多 >
编程相关推荐