Python 在deque被另一个线程修改的情况下,如何存储和访问deque中的值?
我的程序有两个线程——第一个线程用于接收字典列表形式的数据,第二个线程用于将值存储在数据库中Python 在deque被另一个线程修改的情况下,如何存储和访问deque中的值?,python,python-3.x,multithreading,Python,Python 3.x,Multithreading,我的程序有两个线程——第一个线程用于接收字典列表形式的数据,第二个线程用于将值存储在数据库中 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 i
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正在变异”错误。
另外,我如何确保线程无限运行,但
进程_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
特别适合这样:你可以在不同的一端插入和弹出。
这还有一个额外的优点,即您永远无法两次获得相同的元素。这是有道理的,谢谢!如果你不介意的话,我还有一个问题。这个进程最有效的数据结构是什么?@Yuckfou
deque
就足够了。请注意,如上所述,没有线程被启动:process\u ticks(buffer)
已经启动了无限循环,而不是将其推送到线程。这会阻塞主线程。应该改为t2=threading.Thread(target=process\u ticks,args=(buffer,)
。@MisterMiyagi非常感谢,伙计!