queue.SimpleQueue handles more than threadsafe concurrency. It handles reentrancy - it is safe to call queue.SimpleQueue.put in precarious situations where it might be interrupting other work in the same thread. For example, you can safely call it from __del__ methods, weakref callbacks, or signal module signal handlers.

If you need that, use queue.SimpleQueue.

Answer from user2357112 on Stack Overflow
🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
February 23, 2026 - The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved ...
Discussions

multithreading - Learning about Queue module in python (how to run it) - Stack Overflow
Was recently introduced to the queue design in regards to ability to defer processing as well as implementing a "FIFO" etc. Looked through the documentation in attempt to get a sample queue going... More on stackoverflow.com
🌐 stackoverflow.com
Implementing an efficient queue in Python - Stack Overflow
I have been trying to implement a queue in Python, and I've been running into a problem. I am attempting to use lists to implement the queue data structure. However I can't quite figure out how to make enqueue and dequeue O(1) operations. Every example I have seen online, seems to just append ... More on stackoverflow.com
🌐 stackoverflow.com
When do you use queues and tuples instead of lists?
Queues make a lot of sense given that they are FIFO but what are the cases when you'd actually use the import queue and queue.Queue? Anywhere you need a FIFO structure, really, it's hard to explain further than that. Probably the most common example of using it is a breadth first search. It's also used for things like request queues on a web server - when a request comes in you add it to the end of the queue, and each time you are free you process the first request in the queue meaning nothing has to wait too long. Also when would you prefer tuples over lists? Lists are mutable, so aren't they supposed to be superior Sometimes you explicitly do not want mutability, sometimes it's safer to guarantee that the object won't be mutated and a tuple allows you do ensure that is the case. More on reddit.com
🌐 r/learnpython
22
6
June 16, 2025
Stacks and Queues, when to use them?
Career software developer here I almost never use stacks. Not never. But almost never. I mean, obviously we all use stacks every time we call a function but really I don't find much practical use for coding them into the kind of work I do (scientific data processing, web, embedded). I can't honestly think of the last time I used a stack as a stack. Probably when I was parsing something. They're useful for traversing nested data structures and keeping track of what level you're on. OTOH I use queues extensively; almost exclusively; whenever I have to synchronize work among a number of threads or processes. The Python Queue module is great and works with threading, multiprocessing, gevent, etc right out of the box. I use queues (aka circular buffers) in my embedded work as well for buffering data on the device before transmission to the host. For widely distributed computing I like Celery/RabbitMQ. More on reddit.com
🌐 r/learnpython
13
19
February 9, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › queue-in-python
Queue in Python - GeeksforGeeks
July 9, 2024 - Queue is built-in module of Python which is used to implement a queue. queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue. This Queue follows FIFO rule.
🌐
BitDegree
bitdegree.org › learn › python-queue
The Four Types of Python Queue: Definitions and Examples
February 19, 2020 - To simplify working with priority queues, follow the number, element pattern and use the number to define priority. To create Python multiprocessing queues (as opposed to multithreading), use multiprocessing.Queue() function for the multiprocessing module.
🌐
Real Python
realpython.com › queue-in-python
Python Stacks, Queues, and Priority Queues in Practice – Real Python
December 1, 2023 - This means that in the example above, flashing the hazard lights takes precedence over engaging the windshield wipers, even though this ordering doesn’t follow the chronology of events. Both messages have the same priority, important, so the queue should sort them by their insertion order. To be clear, this is a direct consequence of tuple comparison in Python, which moves to the next component in a tuple if the earlier ones didn’t resolve the comparison.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › python queue
Python Queue
October 14, 2024 - The built-in methods in Python are the insert() and pop() functions that are used to add and remove elements from the queue. Lists are a little slow as compared with queues and the reason behind this is when we insert a new element to the list, it requires the shifting of elements by one. And this process takes O(n) time. To better understand this concept, go through the example below:
🌐
W3Schools
w3schools.com › python › python_dsa_queues.asp
Queues with Python
Queues are often mentioned together with Stacks, which is a similar data structure described on the previous page. For Python lists (and arrays), a Queue can look and behave like this:
Find elsewhere
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › queue in python with examples
Queue in Python with Examples - Spark By {Examples}
May 31, 2024 - Priority Queue in Python can be implemented using the queue module. It provides the PriorityQueue class in Python. We have seen it in the example above.
🌐
Javatpoint
javatpoint.com › queue-in-python
Queue in Python - Javatpoint
Queue in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
Medium
basillica.medium.com › working-with-queues-in-python-a-complete-guide-aa112d310542
Working with Queues in Python — A Complete Guide | by Basillica | Medium
March 27, 2024 - Queues are a useful data structure in programming that allow you to add and remove elements in a first in, first out (FIFO) order. Python provides a built-in module called queue that implements different types of queue data structures.
🌐
Python
docs.python.org › 3 › library › asyncio-queue.html
Queues — Python 3.14.4 documentation
February 22, 2026 - Source code: Lib/asyncio/queues.py asyncio queues are designed to be similar to classes of the queue module. Although asyncio queues are not thread-safe, they are designed to be used specifically i...
🌐
Software Testing Help
softwaretestinghelp.com › home › python programming for beginners – free python tutorials › python queue tutorial: how to implement and use python queue
Python Queue Tutorial: How To Implement And Use Python Queue
April 1, 2025 - ... Let us understand the queue with the real-world example of “ Cinema ticket counter ”. While buying the tickets for the movie, people stand in a queue at the ticket counter.
Top answer
1 of 2
23

The for loop is launching a number of worker threads to perform the function defined by "worker". Here is working code that should run on your system in python 2.7.

import Queue
import threading

# input queue to be processed by many threads
q_in = Queue.Queue(maxsize=0)

# output queue to be processed by one thread
q_out = Queue.Queue(maxsize=0)

# number of worker threads to complete the processing
num_worker_threads = 10

# process that each worker thread will execute until the Queue is empty
def worker():
    while True:
        # get item from queue, do work on it, let queue know processing is done for one item
        item = q_in.get()
        q_out.put(do_work(item))
        q_in.task_done()

# squares a number and returns the number and its square
def do_work(item):
    return (item,item*item)

# another queued thread we will use to print output
def printer():
    while True:
        # get an item processed by worker threads and print the result. Let queue know item has been processed
        item = q_out.get()
        print "%d squared is : %d" % item
        q_out.task_done()

# launch all of our queued processes
def main():
    # Launches a number of worker threads to perform operations using the queue of inputs
    for i in range(num_worker_threads):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()

    # launches a single "printer" thread to output the result (makes things neater)
    t = threading.Thread(target=printer)
    t.daemon = True
    t.start()

    # put items on the input queue (numbers to be squared)
    for item in range(10):
        q_in.put(item)

    # wait for two queues to be emptied (and workers to close)   
    q_in.join()       # block until all tasks are done
    q_out.join()

    print "Processing Complete"

main()

Python 3 version per @handle

import queue 
import threading

# input queue to be processed by many threads
q_in = queue.Queue(maxsize=0) 

# output queue to be processed by one thread
q_out = queue.Queue(maxsize=0) 

# number of worker threads to complete the processing
num_worker_threads = 10

# process that each worker thread will execute until the Queue is empty
def worker():
    while True:
        # get item from queue, do work on it, let queue know processing is done for one item
        item = q_in.get()
        q_out.put(do_work(item))
        q_in.task_done()

# squares a number and returns the number and its square
def do_work(item):
    return (item,item*item)

# another queued thread we will use to print output
def printer():
    while True:
        # get an item processed by worker threads and print the result. Let queue know item has been processed
        item = q_out.get()
        print("{0[0]} squared is : {0[1]}".format(item) )
        q_out.task_done()

# launch all of our queued processes
def main():
    # Launches a number of worker threads to perform operations using the queue of inputs
    for i in range(num_worker_threads):
         t = threading.Thread(target=worker)
         t.daemon = True
         t.start()

    # launches a single "printer" thread to output the result (makes things neater)
    t = threading.Thread(target=printer)
    t.daemon = True
    t.start()

    # put items on the input queue (numbers to be squared)
    for item in range(10):
        q_in.put(item)

    # wait for two queues to be emptied (and workers to close)   
    q_in.join()       # block until all tasks are done
    q_out.join()

    print( "Processing Complete" )

main()
2 of 2
3

You can think of the number of worker threads as the number of bank tellers at a bank. So people (your items) stand in line (your queue) to be processed by a bank teller (your worker thread). Queues are actually an easy and well understood mechanism to manage complexities in threads.

I have adjusted your code a bit to show how it works.

import queue
import time
from threading import Thread

def do_work(item):
    print("processing", item)

def source():
    item = 1
    while True:
        print("starting", item)
        yield item
        time.sleep(0.2)
        item += 1

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = queue.Queue(maxsize=0)
def main():
    for i in range(2):
        t = Thread(target=worker)
        t.daemon = True
        t.start()

    for item in source():
        q.put(item)

    q.join()       # block until all tasks are done

main()
🌐
Simplilearn
simplilearn.com › home › resources › software development › queue in python: working with queue data structure in python
Queue in Python: Working With Queue Data Structure in Python
March 5, 2026 - A queue is a built-in module of python used in threaded programming. It stores items sequentially in a FIFO manner. Learn all about the queue in python now!
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Board Infinity
boardinfinity.com › blog › queue-in-python
Queue in Python | Board Infinity
August 9, 2025 - Python's built-in module Queue is used to implement queues. queue. Queue(maxsize) sets a variable's initial value to maxsize, its maximum size.
Top answer
1 of 8
41

As Uri Goren astutely noted above, the Python stdlib already implemented an efficient queue on your fortunate behalf: collections.deque.

What Not to Do

Avoid reinventing the wheel by hand-rolling your own:

  • Linked list implementation. While doing so reduces the worst-case time complexity of your dequeue() and enqueue() methods to O(1), the collections.deque type already does so. It's also thread-safe and presumably more space and time efficient, given its C-based heritage.
  • Python list implementation. As I note below, implementing the enqueue() methods in terms of a Python list increases its worst-case time complexity to O(n). Since removing the last item from a C-based array and hence Python list is a constant-time operation, implementing the dequeue() method in terms of a Python list retains the same worst-case time complexity of O(1). But who cares? enqueue() remains pitifully slow.

To quote the official deque documentation:

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

More critically, deque also provides out-of-the-box support for a maximum length via the maxlen parameter passed at initialization time, obviating the need for manual attempts to limit the queue size (which inevitably breaks thread safety due to race conditions implicit in if conditionals).

What to Do

Instead, implement your Queue class in terms of the standard collections.deque type as follows:

from collections import deque

class Queue:
    '''
    Thread-safe, memory-efficient, maximally-sized queue supporting queueing and
    dequeueing in worst-case O(1) time.
    '''


    def __init__(self, max_size = 10):
        '''
        Initialize this queue to the empty queue.

        Parameters
        ----------
        max_size : int
            Maximum number of items contained in this queue. Defaults to 10.
        '''

        self._queue = deque(maxlen=max_size)


    def enqueue(self, item):
        '''
        Queues the passed item (i.e., pushes this item onto the tail of this
        queue).

        If this queue is already full, the item at the head of this queue
        is silently removed from this queue *before* the passed item is
        queued.
        '''

        self._queue.append(item)


    def dequeue(self):
        '''
        Dequeues (i.e., removes) the item at the head of this queue *and*
        returns this item.

        Raises
        ----------
        IndexError
            If this queue is empty.
        '''

        return self._queue.pop()

The proof is in the hellish pudding:

>>> queue = Queue()
>>> queue.enqueue('Maiden in Black')
>>> queue.enqueue('Maneater')
>>> queue.enqueue('Maiden Astraea')
>>> queue.enqueue('Flamelurker')
>>> print(queue.dequeue())
Flamelurker
>>> print(queue.dequeue())
Maiden Astraea
>>> print(queue.dequeue())
Maneater
>>> print(queue.dequeue())
Maiden in Black

It Is Dangerous to Go Alone

Actually, don't do that either.

You're better off just using a raw deque object rather than attempting to manually encapsulate that object in a Queue wrapper. The Queue class defined above is given only as a trivial demonstration of the general-purpose utility of the deque API.

The deque class provides significantly more features, including:

...iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in operator, and subscript references such as d[-1].

Just use deque anywhere a single- or double-ended queue is required. That is all.

2 of 8
10

You can keep head and tail node instead of a queue list in queue class

class Node:
    def __init__(self, item = None):
        self.item = item
        self.next = None
        self.previous = None


class Queue:
    def __init__(self):
        self.length = 0
        self.head = None
        self.tail = None

    def enqueue(self, value):
        newNode = Node(value)
        if self.head is None:
            self.head = self.tail = newNode
        else:
            self.tail.next = newNode
            newNode.previous = self.tail
            self.tail = newNode
        self.length += 1

    def dequeue(self):
        item = self.head.item
        self.head = self.head.next 
        self.length -= 1
        if self.length == 0:
            self.tail = None
        return item
🌐
Guru99
guru99.com › home › python › python queue: fifo, lifo example
Python Queue: FIFO, LIFO Example
August 12, 2024 - The module is available by default with python, and you don’t need any additional installation to start working with the queue. There are 2 types of queue FIFO (first in first out) and LIFO (last in first out). Step 2) To work with FIFO queue , call the Queue class using the queue module imported as shown below: ... In the case of first in first out, the element that goes first will be the first to come out. Let us work on an example to add an item in a queue.
🌐
W3Schools
w3schools.com › dsa › dsa_data_queues.php
DSA Queues
But to explicitly create a data structure for queues, with basic operations, we should create a queue class instead. This way of creating queues in Python is also more similar to how queues can be created in other programming languages like C and Java.
🌐
Programiz
programiz.com › dsa › queue
Queue Data Structure and Implementation in Java, Python and C/C++
The complexity of enqueue and dequeue operations in a queue using an array is O(1). If you use pop(N) in python code, then the complexity might be O(n) depending on the position of the item to be popped. ... When data is transferred asynchronously between two processes.The queue is used for synchronization. For example: IO Buffers, pipes, file IO, etc
🌐
Intellipaat
intellipaat.com › home › blog › queue in python – implementation explained
Queue in Python: How to Implement Queue in Python
October 14, 2025 - The function uses the append() method available for lists in Python to add the specified element to the end of the queue list. The example usage demonstrates how to create an empty queue (my_queue) and enqueue three elements: ‘apple’, ‘banana’, and ‘cherry’. After enqueuing the elements, the print(my_queue) statement outputs [‘apple’, ‘banana’, ‘cherry’], indicating that the elements have been successfully enqueued in the desired order.