queue
The Python queue module provides reliable thread-safe implementations of the queue data structure. It is commonly used for task scheduling and managing work between multiple threads.
Here’s a quick example:
Key Features
- Provides thread-safe FIFO, LIFO, and priority queues
- Supports blocking and non-blocking operations
- Allows a maximum size to be set for queues
- Includes a lightweight SimpleQueue without task tracking
- Supports graceful shutdown of queues with Queue.shutdown() (Python 3.13+)
Frequently Used Classes and Functions
| queue.Queue | Class | Provides a first-in, first-out (FIFO) queue |
| queue.Queue.put() | Method | Adds an item to the queue |
| queue.Queue.get() | Method | Removes and returns an item from the queue |
| queue.Queue.qsize() | Method | Returns the approximate size of the queue |
| queue.Queue.empty() | Method | Checks whether the queue is empty |
| queue.Queue.full() | Method | Checks whether the queue is full |
| queue.LifoQueue | Class | Provides a last-in, first-out (LIFO) queue |
| queue.PriorityQueue | Class | Provides a queue where entries are retrieved by priority |
| queue.SimpleQueue | Class | Provides an unbounded FIFO queue without task tracking |
Examples
Using a LIFO queue:
Using a priority queue:
Common Use Cases
- Managing task scheduling in multi-threaded applications
- Implementing producer-consumer patterns
- Prioritizing tasks using priority queues
Real-World Example
Consider a scenario where multiple worker threads need to process tasks concurrently. In this situation, you can use the queue module to manage these tasks efficiently:
In this example, you use the queue module to distribute tasks among two worker threads, ensuring that each task is processed exactly once.
Related Resources
Tutorial
Python Stacks, Queues, and Priority Queues in Practice
In this tutorial, you'll take a deep dive into the theory and practice of queues in programming. Along the way, you'll get to know the different types of queues, implement them, and then learn about the higher-level queues in Python's standard library. Be prepared to do a lot of coding.
For additional information on related topics, take a look at the following resources: