Linux

Python Queue

In real life, a queue is a line of customers waiting for service of some kind. In most cases, the first customer in line is the next customer to be served. There are exceptions, though. At airports, customers whose flights are leaving soon are sometimes taken from the middle of the queue. At supermarkets, a polite customer might let someone with only a few items go first.
Queuing policy decides who goes next.The simplest queueing policy is called FIFO, for "first-in-first-out."
Let us discuss the FIFO with example. According to python docs , class Queue.Queue(maxsize=0) Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
Syntax
q= Queue.Queue(maxsize)

total number of items can be inserted is equal to maxsize
Python  FIFO Queue using Queue.Queue()
FIFO Queue
Click to view code


To initialize FIFO Python queue we use q= Queue.Queue()
q.put(i) used to put element in the Python Queue
q.get() used to get the elements from the queue or you can say it removes the element from the Python queue.
q.empty() return True if the Python queue is empty, False otherwise.

Now let us discuss Python LIFO queue policy.
LifoQueue uses last-in, first-out ordering (normally associated with a stack data structure). Syntax
q = Queue.LifoQueue()
q is Python LIFO Queue.
Python LIFO queue by using LifoQueue
Python LIFO Queue
Click to view code
Value 4 went first came first, same for other values.

Let us discuss Python PriorityQueue.
The lowest valued entries are retrieved first. A typical pattern for entries is a tuple in the form: (priority_number, data). Syntax to create Priority Queue
q= Queue.PriorityQueue()
q is Python Priority Queue.
Python Priority Queue using Queue.PriorityQueue()
Python Priority Queue
Click to view code
q.put(priority, data) put priority and data, Output shows priority number. If you want to show data part do as shown in program.
Python Priority Queue with values
Python Priority Queue
Click to view code
What amendments have been done in above program, make one argument q.put((8, "low")) It forms Python tuples in the list, (1, 'Very important') is a Python tuple in list q Python queue. The q.get returns each Python tuple from the list , so q.get[1] gives the second value from the Python tuple.





admin