How to clear a multiprocessing queue in python

后端 未结 3 1489
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 21:32

I just want to know how to clear a multiprocessing queue in python like a normal python queue. For instance:

from multiprocessing import Queue  # multiproces         


        
相关标签:
3条回答
  • 2021-01-03 21:42

    So, I take look at Queue class, and you may to try this code:

    while not some_queue.empty():
        some_queue.get()  # as docs say: Remove and return an item from the queue.
    
    0 讨论(0)
  • 2021-01-03 21:49

    Ask for forgiveness rather than permission; just try to empty the queue until you get the Empty exception, then ignore that exception:

    from Queue import Empty
    
    def clear(q):
        try:
            while True:
                q.get_nowait()
        except Empty:
            pass
    

    Better yet: is a built-in class missing the method you want? Subclass the built-in class, and add the method you think should be there!

    from Queue import Queue, Empty
    
    class ClearableQueue(Queue):
    
        def clear(self):
            try:
                while True:
                    self.get_nowait()
            except Empty:
                pass
    

    Your ClearableQueue class inherits all the goodness (and behavior) of the built-in Queue class, and has the method you now want.

    Simply use q = ClearableQueue() in all places where you used q = Queue(), and call q.clear() when you'd like.

    0 讨论(0)
  • 2021-01-03 21:56

    There is no direct way of clearing a multiprocessing.Queue.

    I believe the closest you have is close(), but that simply states that no more data will be pushed to that queue, and will close it when all data has been flushed to the pipe.

    0 讨论(0)
提交回复
热议问题