Question

I have a queue (from the Queue module), and I want to get indexed access into it. (i.e., being able to ask for item number four in the queue, without removing it from the queue.)

I saw that a queue uses a deque internally, and deque has indexed access. The question is, how can I use the deque without (1) messing up the queue, (2) breaking thread-safety.

Was it helpful?

Solution

import Queue

class IndexableQueue(Queue):
  def __getitem__(self, index):
    with self.mutex:
      return self.queue[index]

It's of course crucial to release the mutex whether the indexing succeeds or raises an IndexError, and I'm using a with statement for that. In older Python versions, try/finally would be used to the same effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top