在python中有一个内置的heapq
为您提供 push
、pop
、nlargest
、nsmallest
... 等的算法,您可以将这些算法应用于列表。但是,还有 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. TheQueue
class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see thethreading
module.
heapq
模块不提供锁定,并且对标准 list
对象进行操作,这些对象并不是线程安全的。
事实上,PriorityQueue
implementation 在底层使用 heapq
来完成所有优先级排序工作,使用基本的 Queue
类提供锁定以使该线程安全。见 source code了解详情。
这使得 heapq
模块更快;没有锁定开销。此外,您可以以不同的新颖方式自由使用各种 heapq
函数,PriorityQueue
仅提供直接排队功能。
关于python - python中的heapq和PriorityQueue有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991716/