【问题标题】:Having the deque with the advantages of Queue in a thread在线程中拥有具有队列优势的双端队列
【发布时间】:2019-11-11 06:49:46
【问题描述】:

我需要一个结构,我可以将 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 函数)更好?

【问题讨论】:

    标签: python python-3.x multithreading queue deque


    【解决方案1】:

    如何创建自己的队列来混合两者的优点?

    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
    

    【讨论】:

    • 两种解决方案都不错,但我觉得这个更优雅,谢谢!
    • 一旦队列大小增加到超过双端队列大小,它就没有机会再次将其减小到双端队列大小。这意味着您将在对象处于活动状态时将“去队列”对象保留在队列中。
    【解决方案2】:

    不确定哪个更好,但这里有一个添加 wait on popthreading.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 
    

    【讨论】:

    • 一个小错误:应该是if not (len(self) -1): 另外,在这个公式中,deque.append() 和 .pop() 作为 LIFO 工作。 Queue.put() 和 .get() 动作中的等价物是 FIFO
    猜你喜欢
    • 2016-01-19
    • 2016-01-23
    • 1970-01-01
    • 2014-12-16
    • 2018-07-02
    • 2017-05-06
    • 2018-02-16
    • 2017-06-24
    • 1970-01-01
    相关资源
    最近更新 更多