examining items in a python Queue

前端 未结 3 628

Is it possible to examine items in a Queue in Python without calling .get()? As per the docs, indexing is not allowed in Queue. I need to check if

3条回答
  •  借酒劲吻你
    2020-12-15 21:24

    It is NOT safe to simply access the underlying queue.

    The safe way to do it is to extend the Queue class. If you return the underlying dequeue object, you will NOT be getting a copy, you get the live object.

    The result of this is that it can change while you are iterating it - which will result in an exception if another thread inserts into the queue during your iteration.

    Knowing that python uses the GIL, you can safely use list(q.queue), because list() will never cause a context switch.

    It's better to use the same lock the get() function uses, and not make assumptions about the GIL:

    import queue
        
    class SnapshotQueue(queue.Queue):
        def snapshot(self):
            with self.mutex
                return list(self.queue)
    

    That class can be used safely instead of a regular queue, and it will return a snapshot of the queue state... within a mutex and without causing issues in the underlying queue operation.

提交回复
热议问题