Search code examples
pythonpriority-queue

How to enqueue and dequeue objects to/from a priority queue in python 3


I am writing a program in python 3 to enqueue and dequeue objects called packets. These packets have priorities associated with them and I would like the priority queue to dequeue the packets in priority order. Below is the code:

if(pkt.pktId != -1):
      print("pktID: ", pkt.pktId, "srcID :", pkt.srcID)
      arbiter1.put(pkt.pri, pkt)

      while ((arbiter1.empty()==False) and (queueList[0].full()==False)):
           x= arbiter1.get()
           queueList[0].put(arbiter1.get())

Pkt is of type Packet Class() and contains multiple fields. One of the fields is pri.

When I dequeue "x" and print x, it gives me an int rather than the object pkt.


Solution

  • I am assuming you're using the stdlib priority queue class:

    import queue
    arbiter1 = queue.PriorityQueue()
    

    In this case, when you call arbiter1.put(pkt.pri, pkt) you were actually passing in the priority integer as the "item" and the packet as the "block" flag:

    def put(self, item, block=True, timeout=None):
        ...
    

    Instead, you can pass tuples in:

    arbiter1.put((pkt.pri, pkt))
    

    And get tuples out:

    priority, pkt = arbiter1.get()
    

    If packets don't have any ordering defined and there may be packets with equal priorities, then you'll also want to use a tie-breaker in the tuples. Simple integers will work

    import itertools
    tiebreaker = itertools.count()
    
    arbiter1.put((pkt.pri, next(tiebreaker), pkt))
    priority, _, pkt = arbiter1.get()