1

I have a queue as:

from Queue import Queue
myqueue = Queue()

How do I remove lets say 10 elements from the queue? I currently have the following:

for i in range(10):
    myqueue.get()

is there a beautiful way for this? Currently the dummy variable i is not being used, is there a way to avoid that from happening?

Har
  • 3,727
  • 10
  • 41
  • 75

1 Answers1

2

Short answer: no.

A queue is meant to be used for concurrent access (see https://docs.python.org/2/library/queue.html), where multiple workers fetch items from a single queue.

Simple example: your worker retrieves 10 items. On the first item, the worker crashes for some runtime error, say due to memory exhaustion or disk corruption. What happens to the remaining 9 items? Should they be put back in the queue for other workers to fetch them?

Could you elaborate a bit more on what you are trying to do, by fetching more than one item at the time? How many workers do you have? Why 10 and not 100? Etc.

lorenzog
  • 3,483
  • 4
  • 29
  • 50
  • I am using a simple queue in a single thread. Thank you pointing out the concurrent access thats useful to know. – Har Apr 02 '14 at 16:12
  • 1
    @user1932405 if you're using a queue in a single thread, why not just use `list` as a queue? Intuitively I feel like it must be faster. – Adam Smith Apr 02 '14 at 16:28
  • 1
    @user1932405: If you're only using a single thread, you should probably use a `deque` from the `collections` module, rather than a `Queue`. It has a somewhat more flexible API, but still doesn't have a way of dropping 10 items from the queue at a time. – Blckknght Apr 02 '14 at 17:55
  • Could you remove more than 10 items from a list at any one time? Seems like ive used the wrong data structure. – Har Apr 03 '14 at 08:20
  • 1
    @user1932405 you could slice a list: http://stackoverflow.com/questions/509211/pythons-slice-notation – lorenzog Apr 03 '14 at 08:41
  • 1
    Found the answer if I do queue.queue.clear() then that works, but must be careful that no one writes to that queue during that time. Therefore use the mutex of with queue.mutex: queue.queue.clear() – Har Apr 10 '14 at 13:05