# Heapq vs. Q.PriorityQueue

{% embed url="<https://stackoverflow.com/questions/36991716/whats-the-difference-between-heapq-and-priorityqueue-in-python>" %}

`Queue.PriorityQueue` is a thread-safe class, while the `heapq`module makes no thread-safety guarantees. From the [`Queue`module documentation](https://docs.python.org/2/library/queue.html):

> 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.

The `heapq` module offers no locking, and operates on standard `list` objects, which are not meant to be thread-safe.

In fact, the `PriorityQueue` *implementation* uses `heapq` under the hood to do all prioritisation work, with the base `Queue` class providing the locking to make this thread-safe. See the [source code](https://hg.python.org/cpython/file/v2.7.11/Lib/Queue.py#l212)for details.

This makes the `heapq` module faster; there is no locking overhead. In addition, you are free to use the various `heapq` functions in different, novel ways, the `PriorityQueue` only offers the straight-up queueing functionality.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sisyphus.gitbook.io/project/python-notes/heapq-vs.-q.priorityqueue.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
