如何在 Python 中实现优先级队列?

pythonserver side programmingprogramming更新于 2026/2/15 13:32:17

简介...

队列模块提供先进先出 (FIFO)、后进先出 (LIFO) 数据结构,适用于多线程编程。队列可用于在创建者和消费者线程之间安全地传递数据或任何广泛的信息,例如会话详细信息、路径、变量等。锁定通常由调用者处理。

注意:本讨论假设您已经了解队列的一般性质。如果不了解,您可能需要在继续之前阅读一些参考资料。

1.让我们实现一个基本的 FIFO 队列。

import 队列
fifo = 队列.Queue()

# 将数字放入队列
for i in range(5):
fifo.put(i)

# 如果不为空,则从队列中获取数字
print(f"Ouput \n")
while not fifo.empty():
print(f" {fifo.get()} ")

输出

0
1
2
3
4

2. 上述示例使用单个线程来显示如何按照插入顺序从队列中删除元素。

3.让我们实现一个基本的 LIFO 队列。

import 队列
lifo = 队列.LifoQueue()

# 将数字放入队列
for i in range(5):
lifo.put(i)

print(f"Ouput \n")
# 如果不为空,则从队列中获取数字
while not lifo.empty():
print(f" {lifo.get()} ")

输出

4
3
2
1
0

4. 上述示例显示,最近放入队列的内容通过 get 被移除。

5. 最后,我们将了解如何实现优先级队列。

有时,队列中项目的处理顺序需要基于这些项目的优先级,而不仅仅是它们被创建或添加到队列的顺序。例如,在生产中运行的业务关键型作业需要最高的 CPU 并优先于开发人员想要打印的打印作业。 PriorityQueue 使用队列内容的排序顺序来决定要检索哪个项目。

import 队列
import 线程

# 获取优先级和描述并验证优先级的类
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(90, 'Developer-Print job'))
q.put(Job(2, 'Business-Report job'))
q.put(Job(1, 'Business-Critical Job'))

# 处理作业
def process_job(q):
while True:
next_job = q.get()
print(f" *** Now, Processing the 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.setDaemon(True)
w.start()

q.join()

输出

job: Developer-Print job
New job: Business-Report job
New job: Business-Critical Job

输出

*** Now, Processing the job - Business-Critical Job
*** Now, Processing the job - Business-Report job
*** Now, Processing the job - Developer-Print job

6. 此示例有多个线程使用作业,这些作业根据调用 get() 时队列中项目的优先级进行处理。处理顺序基于业务关键性,与添加顺序无关。


相关文章


有用资源