I am trying to build a priority queue that never blocks on
put(), and discards the lowest priority item if it is full and user attempts to
put() a higher priority item. I will be using it as a URL queue for a web crawler, where the queue scores represent relevance to a search query (so that more relevant sites are fetched first).
class URLQueue(Queue): """Non-blocking priority queue that tosses lowest priority (highest score) item when full, if attempt to add higher priority item ...""" def _init(self, maxsize): # this overrides queue methods, see cpython/Lib/queue.py self.queue = sortedcontainers.SortedList() def _get_nowait(self): # pop the first (most important) item off the queue return self.queue.pop(0) def _get(self): # pop the first (most important) item off the queue return self.queue.pop(0) def __drop(self): # drop the last (least important) item from the queue # no consumer will get a chance to process this item, so # we must decrement the unfinished count ourselves dropped = self.queue.pop() self.task_done() return dropped # in case we need to add it back (if item we're attempting to put has higher score def _put(self, item): self.queue.add(item) def put_nowait(self, new_item): """ compare the new_item we are attempting to add to last item in queue (worst score), if item we're attempting to add has better score, put it on queue, otherwise put previous max item back on queue and drop new item """ try: super().put_nowait(new_item) except Full: lowest_scored_item = self.__drop() if new_item > lowest_scored_item: super().put_nowait(lowest_scored_item) else: super().put_nowait(new_item) def put(self, item): # this queue never blocks, so we can call put_nowait() directly super().put(item, block=False)
I am interested in any feedback/advice, but specifically I'm wondering:
Is there a better way to do this than using
sortedcontainersto represent the internal queue? Is there a way that I could implement something using only builtins and standard library functions?
Will the way I've done this cause any issues with threading? I will be putting/getting from the queue from multiple threads, and don't know if the way this is done will break something.
Are there alternative data structures I could consider for maintaining a URL queue that prioritizes links based on some type of "relevance score"?
NOTE: I would like to give credit for the original idea of how to do this to this answer.