python - python中的heapq和PriorityQueue有什么区别?

标签 python data-structures heap priority-queue

在python中有一个内置的heapq为您提供 pushpopnlargestnsmallest... 等的算法,您可以将这些算法应用于列表。但是,还有 queue.PriorityQueue似乎支持或多或少相同功能的类。有什么区别,您什么时候会使用其中一种?

最佳答案

Queue.PriorityQueue 是一个线程安全的类,而 heapq 模块不保证线程安全。来自 Queue module documentation :

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.

heapq 模块不提供锁定,并且对标准 list 对象进行操作,这些对象并不是线程安全的。

事实上,PriorityQueue implementation 在底层使用 heapq 来完成所有优先级排序工作,使用基本的 Queue 类提供锁定以使该线程安全。见 source code了解详情。

这使得 heapq 模块更快;没有锁定开销。此外,您可以以不同的新颖方式自由使用各种 heapq 函数,PriorityQueue 仅提供直接排队功能。

关于python - python中的heapq和PriorityQueue有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991716/

相关文章:

python - 有没有办法使用 nltk 将标记句子中的标记重复 2 次或更多次?

python - 如何在 Windows 上更新 SSL 证书?

python - 使用 Python/BeautifulSoup 迭代 .txt 文件中的多个 URL

algorithm - Hash表操作的时间复杂度是O(1)还是O(N)?

java - 策略棋盘游戏 AI 的高效棋盘表示

java - 构建自下而上的堆

python - 使用 GitHub API 检查用户是否存在

python - 如何从python中通过heapq实现的优先级队列中删除log(n)中的元素?

java - 自定义数据结构(元素+权重)

c - 'rooms' 之前的预期说明符限定符列表