SoFunction
Updated on 2024-10-28

Python QueueQueue and PriorityQueue Analysis

Python Queues Queue and PriorityQueue

Python's Queue module

FIFO implementation for multi-threaded programming. It can be used in the producer (producer) and consumer (consumer) between the thread-safe (thread-safe) to pass messages or other data, so that multiple threads can share the same Queue instance.

  • FIFO: First in, First out.first-in-first-out (FIFO)
  • LIFO: Last in, First out.

Features of PriorityQueue, a priority queue

  • Given a Priority
  • Each pop operation returns an item with the highest priority.
from queue import Queue# FIFO queue
from queue import PriorityQueue# Priority queue
import time
# Queue: FIFO
q = Queue()# Create an empty queue with an unspecified queue size
# Determine if the queue is empty
# When a queue is empty, it will be blocked if you fetch it with get, so fetching the queue is usually done using the
The #get_nowait() method, which throws an Empty exception when fetching values from an empty queue.
# So the more common approach is to first determine if a queue is empty, and if not take the value of
 
 
print(())
# Queue operations: store--put() fetch--get()
('page1')
('page2')
('page3')
 
print(())
# Determine if the queue is full
print(())
 
q1 = Queue(3)# Specify the queue size (indicating how many elements the queue can hold at most) when creating the queue
('1')
('1')
('1')
print(())
 
 
q2 = Queue(3)
('1')
('2')
('3')
value = ()# Follow the principle of FIFO
print(value)
print(())
 
#Store data - blocking
q3 = Queue(3)
(1)
(2)
(3)
# (4)# If the queue is full, wait (block) until the queue is free and then deposit the value into the queue.
 
# Fetch data - blocking
q4 = Queue(3)
(1)
value = ()#1, the queue is empty.
print('q4:',value)
# value = ()# Block until a new value is added to the queue, then remove it and end the blocking.
 
#Non-blocking
q5 = Queue(3)
(1)
 
#1.
print(':',())#Number of elements in the current queue
#Method 1:
# while not ():
# value2 = (block=False)# block is Ture, which means blocking, otherwise non-blocking. Non-blocking is "force fetch."
#     print('q5:',value2)
#Method 2:
while ()>0:
    value2 = (block=False)
    print('q5:',value2)
 
print(':',())
#exist
q6 = Queue(3)
 
#Method 1:
# print()# Get the maximum capacity of the queue
# i = 0
# while i<:
#     (i)
#     i+=1
 
#Method 2:
while not ():
    (1,block=False)#Non-blocking
 
 
'''------------------------------ other properties and methods -----------------------------'''
q7 = Queue(3)
# (block=False)
print(())
try:
    (timeout=2)# of blocking hours
except:
    pass
print(())
 
q8 = Queue(3)
# q8.get_nowait() # force fetch
 
'''------------------------------ priority queue -----------------------------'''
q = PriorityQueue()
 
# Format: ((number, value))
# Characteristics: the smaller the number, the higher the priority
((1,'lori'))
((-1,'Jseon'))
((10,'King'))
 
i = 0
while i<():
    print(())

python implements a priority queue

import heapq
 
class PriorityQueue(object):
    def __init__(self):
        self._queue = []        # Create an empty list to hold the queue
        self._index = 0        The # pointer is used to record the order of push
    
    def push(self, item, priority):
        """The queue consists of tuples of the form (priority, index, item)"""
        (self._queue, (-priority, self._index, item)) 
        self._index += 1
        
    def pop(self):
        return (self._queue)[-1]    # Returns the item with the highest priority
 
class Item(object):
    def __init__(self, name):
         = name
 
    def __repr__(self):
        return 'Item: {!r}'.format()
 
if __name__ == '__main__':
    q = PriorityQueue()
    (Item('foo'), 5)
    (Item('bar'), 1)
    (Item('spam'), 3)
    (Item('grok'), 1)
    for i in range(4):
        print(q._queue)
        print(())

Four pop() operations are performed on the queue and the following results are printed:

[(-5, 0, Item: 'foo'), (-1, 1, Item: 'bar'), (-3, 2, Item: 'spam'), (-1, 3, Item: 'grok')]
Item: 'foo'
[(-3, 2, Item: 'spam'), (-1, 1, Item: 'bar'), (-1, 3, Item: 'grok')]
Item: 'spam'
[(-1, 1, Item: 'bar'), (-1, 3, Item: 'grok')]
Item: 'bar'
[(-1, 3, Item: 'grok')]
Item: 'grok'

It is possible to observe how pop() returns an item with the highest priority. For items with the same priority (bar and grok), they are returned in the order in which they were inserted into the queue.

The core of the code utilizes the heapq module, and as mentioned before, () returns the smallest value item, so the value of priority needs to be made negative in order for the queue to sort each item in a sequential order from highest to lowest priority.

python PriorityQueue

An ordinary queue is a first-in-first-out data structure where elements are appended at the end of the queue and removed from the head of the queue. In a priority queue, elements are given priority.

When elements are accessed, those with the highest priority are deleted first. Priority queues are characterized by the highest priority first-out behavior. It is usually implemented using a heap data structure.

We can use the priority queue elements are given priority of this feature to save to the current state of a number of the largest element value, so that the higher the priority then elements can be processed first, PriorityQueue belongs to the queue module in a class, which is often used in three methods: declare a priority queue, to the priority queue to add elements to the priority queue to the priority queue to remove elements from the priority queue and removing elements from the priority queue.

  • ① Declare a priority queue: ()
  • ② add elements to the queue: (self, item, block=True, timeout=None)
  • ③ Remove elements from the queue: (self, block=True, timeout=None)

When adding elements to the queue, the first element value indicates the priority of the element, and the smaller the value, the higher the priority, so the first element of the queue is the highest priority, and often added to the queue of elements of the type of tuple so that you can save multiple values in the queue.

Here are specific examples

import queue
if __name__ == '__main__':
    queue = ()
    ((100, 100))
    ((-12, -7))
    ((7, 8))
    while not ():
        print(())

Output results:

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.