在一个线程中拥有deque和Queue的优点
Having the deque with the advantages of Queue in a thread
我需要一个结构,在该结构中我可以将 pop() 和 append() 到右侧(就像双端队列一样),同时如果结构为空则阻塞并等待(就像队列一样)。我可以直接使用 Queue,但我还需要 deque 的好特性,如果结构已满,可以在不阻塞的情况下删除项目。
from collections import deque
d = deque(maxlen=2)
d.append(1)
d.append(2)
d.append(3) # d should be [2,3] (it is the case)
d.pop()
d.pop()
d.pop() # should wait (not the case)
子类化 deque(让它等待)或 Queue(添加 popLeft 函数)更好吗?
如何创建自己的队列来混合两者的优点?
import queue as Queue
from collections import deque
class QueuePro:
def __init__(self, maxlenDeque):
self.deque = deque(maxlen=maxlenDeque)
self.queue = Queue.Queue()
def append(self, elem):
self.deque.append(elem)
self.queue.put(elem)
def pop(self):
if(not self.deque):
self.queue.get()
else:
self.deque.pop()
self.queue.get()
q2 = QueuePro(2)
q2.append(1)
q2.append(2)
q2.pop()
q2.pop()
q2.pop()
#waiting
不确定哪个更好,但这是添加 wait on pop 和 threading.Event
的想法
from collections import deque
from threading import Event
class MyDeque(deque):
def __init__(self, max_length):
super().__init__(maxlen=max_length)
self.not_empty = Event()
self.not_empty.set()
def append(self, elem):
super().append(elem)
self.not_empty.set()
def pop(self):
self.not_empty.wait() # Wait until not empty, or next append call
if not (len(q) - 1):
self.not_empty.clear()
return super().pop()
q = MyDeque(2)
q.append(1)
q.append(2)
q.append(3)
q.pop()
q.pop()
q.pop() # Waits
我需要一个结构,在该结构中我可以将 pop() 和 append() 到右侧(就像双端队列一样),同时如果结构为空则阻塞并等待(就像队列一样)。我可以直接使用 Queue,但我还需要 deque 的好特性,如果结构已满,可以在不阻塞的情况下删除项目。
from collections import deque
d = deque(maxlen=2)
d.append(1)
d.append(2)
d.append(3) # d should be [2,3] (it is the case)
d.pop()
d.pop()
d.pop() # should wait (not the case)
子类化 deque(让它等待)或 Queue(添加 popLeft 函数)更好吗?
如何创建自己的队列来混合两者的优点?
import queue as Queue
from collections import deque
class QueuePro:
def __init__(self, maxlenDeque):
self.deque = deque(maxlen=maxlenDeque)
self.queue = Queue.Queue()
def append(self, elem):
self.deque.append(elem)
self.queue.put(elem)
def pop(self):
if(not self.deque):
self.queue.get()
else:
self.deque.pop()
self.queue.get()
q2 = QueuePro(2)
q2.append(1)
q2.append(2)
q2.pop()
q2.pop()
q2.pop()
#waiting
不确定哪个更好,但这是添加 wait on pop 和 threading.Event
from collections import deque
from threading import Event
class MyDeque(deque):
def __init__(self, max_length):
super().__init__(maxlen=max_length)
self.not_empty = Event()
self.not_empty.set()
def append(self, elem):
super().append(elem)
self.not_empty.set()
def pop(self):
self.not_empty.wait() # Wait until not empty, or next append call
if not (len(q) - 1):
self.not_empty.clear()
return super().pop()
q = MyDeque(2)
q.append(1)
q.append(2)
q.append(3)
q.pop()
q.pop()
q.pop() # Waits