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.
Python provides a thread-safe queue in the queue. Queue class. A queue is a data structure on which items can be added by a call to put() and from which items can be retrieved by a call to get().
Python queue PriorityQueue is thread-safe, but heapq doesn't guarantee thread safety. PriorityQueue implements locking to ensure thread safety, thus it is slower than heapq.
get() method in python is a blocking function.
Additionally, append and pop operations on deques are also thread safe and memory efficient. These features make deques particularly useful for creating custom stacks and queues in Python.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With