gpt4 book ai didi

python - 在一个线程中拥有deque和Queue的优点

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:48 25 4
gpt4 key购买 nike

我需要一个结构,在该结构中我可以将 pop() 和 append() 到右侧(就像双端队列一样),同时让结构阻塞并在它为空时等待(就像队列一样)。我可以直接使用队列,但我还需要 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 函数)更好?

最佳答案

不确定哪个更好,但这里有一个使用 threading.Event 添加 wait on pop 的想法

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

关于python - 在一个线程中拥有deque和Queue的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com