queue: Thread-Safe FIFO Implementation

1.1 Basic FIFO Queue

The following is programming codes:

import queue

q = queue.Queue()

for i in range(5):
    q.put(i)


while not q.empty():
    print(q.get(), end=' ')
print()

This example uses a single thread to illustrate that elements are removed from the queue in the same order in which they are inserted.

the result :

D:\Python39\python.exe D:/My_Project/queque_demo1.py
0 1 2 3 4 

Process finished with exit code 0

1.2 LIFO Queue

The following is programming codes:

import queue

q = queue.LifoQueue()

for i in range(5):
    q.put(i)


while not q.empty():
    print(q.get(), end=' ')
print()

the result:

D:\Python39\python.exe D:/My_Project/queque_demo1.py
4 3 2 1 0 

Process finished with exit code 0

1.3 Priority Queue

The following is programming codes:

import functools
import queue
import threading


@functools.total_ordering
class Job:

    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print('New job:', description)
        return

    def __eq__(self, other):
        try:
            return self.priority == other.priority
        except AttributeError:
            return NotImplemented

    def __lt__(self, other):
        try:
            return self.priority < other.priority
        except AttributeError:
            return NotImplemented


q = queue.PriorityQueue()

q.put(Job(3, 'Mid-level job'))
q.put(Job(10, 'low-level job'))
q.put(Job(1, 'Important job'))


def process_job(q):
    while 1:
        next_job = q.get()
        print('Processing job:', next_job.description)
        q.task_done()


workers = [
    threading.Thread(target=process_job, args=(q,)),
    threading.Thread(target=process_job, args=(q,)),
]

for w in workers:
    w.daemon = True
    w.start()
q.join()

The result:

D:\Python39\python.exe D:/My_Project/queque_demo1.py
New job: Mid-level job
New job: low-level job
New job: Important job
Processing job: Important job
Processing job: Mid-level job
Processing job: low-level job

Process finished with exit code 0
04-09 16:32