我无法确定以下双端队列是否是线程安全的.
简而言之,我创建了一个带有双端队列的类,它在新线程中每1秒显示一次其内容(因此在打印时不会暂停主程序).
deque是从主线程填充的,所以基本上应该有碰撞的机会.
但是,使用类方法填充deque,因此实际上它是从实例本身访问的,因此来自同一个线程.
这是简化的代码:
import threading
import time
from collections import deque
class MyQueue(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.q = deque()
self.start()
def run(self):
# pop out queue items every 1 sec
# (please ignore empty deque for now)
while True:
print self.q.popleft()
time.sleep(1)
def add_to_q(self, val):
# this function is called from outside
self.q.append(val)
# main
# fill the queue with values
qu = MyQueue()
for i in range(1:100):
qu.add_to_q(i)
Run Code Online (Sandbox Code Playgroud)
因此,虽然在实例中添加和删除队列中的项目,但是由于从实例外部调用添加函数,是否存在风险?
编辑:
因为我需要修改我的双端队列中的项目,所以我不得不使用Deque.我所做的是:roatate()到给定的项目,弹出它,修改,推回它并旋转()它回到它原来的位置.
除非我找到一种在队列中实现修改项目的方法,否则我将不得不坚持使用Deque