Priority URL queue that does not block on put()












0












$begingroup$


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).



Here is the code:



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[0] > lowest_scored_item[0]:
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:




  1. Is there a better way to do this than using sortedcontainers to represent the internal queue? Is there a way that I could implement something using only builtins and standard library functions?


  2. 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 ...


  3. Are there alternative data structures I could consider for maintaining a URL queue that prioritizes links based on some type of "relevance score"?



Thanks!





NOTE: I would like to give credit for the original idea of how to do this to this answer.










share|improve this question











$endgroup$

















    0












    $begingroup$


    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).



    Here is the code:



    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[0] > lowest_scored_item[0]:
    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:




    1. Is there a better way to do this than using sortedcontainers to represent the internal queue? Is there a way that I could implement something using only builtins and standard library functions?


    2. 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 ...


    3. Are there alternative data structures I could consider for maintaining a URL queue that prioritizes links based on some type of "relevance score"?



    Thanks!





    NOTE: I would like to give credit for the original idea of how to do this to this answer.










    share|improve this question











    $endgroup$















      0












      0








      0





      $begingroup$


      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).



      Here is the code:



      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[0] > lowest_scored_item[0]:
      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:




      1. Is there a better way to do this than using sortedcontainers to represent the internal queue? Is there a way that I could implement something using only builtins and standard library functions?


      2. 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 ...


      3. Are there alternative data structures I could consider for maintaining a URL queue that prioritizes links based on some type of "relevance score"?



      Thanks!





      NOTE: I would like to give credit for the original idea of how to do this to this answer.










      share|improve this question











      $endgroup$




      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).



      Here is the code:



      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[0] > lowest_scored_item[0]:
      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:




      1. Is there a better way to do this than using sortedcontainers to represent the internal queue? Is there a way that I could implement something using only builtins and standard library functions?


      2. 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 ...


      3. Are there alternative data structures I could consider for maintaining a URL queue that prioritizes links based on some type of "relevance score"?



      Thanks!





      NOTE: I would like to give credit for the original idea of how to do this to this answer.







      python multithreading sorting queue priority-queue






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago







      J. Taylor

















      asked 2 hours ago









      J. TaylorJ. Taylor

      1116




      1116






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215308%2fpriority-url-queue-that-does-not-block-on-put%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215308%2fpriority-url-queue-that-does-not-block-on-put%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to reconfigure Docker Trusted Registry 2.x.x to use CEPH FS mount instead of NFS and other traditional...

          is 'sed' thread safe

          How to make a Squid Proxy server?