🌐
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 ...
🌐
Stack Overflow
stackoverflow.com › questions › 35442782 › python-2-7-threading-queue-reuse-threads
multithreading - Python 2.7 threading queue, reuse threads - Stack Overflow
import urllib2, time from threading import Thread from Queue import Queue # Set up global variables num_threads = 5 queue = Queue() urlList = [ "http://google.com", "http://googleeeeeee1111.com" ] def notify(i, q): print "Thread %s: started" % i url = q.get() print "Thread %s: notification sent for site: %s" % (i, url) q.task_done() def make_requests(): while True: for url in urlList: try: request = urllib2.urlopen(url) responseCode = request.getcode() # If the response code was 200, do something if responseCode == 200: print "URL: %s - Success %d" % (url, responseCode) else: print "Bad respon
🌐
Python
docs.python.org › 2 › library › queue.html
8.10. Queue — A synchronized queue class — Python 2.7.18 documentation
If maxsize is less than or equal to zero, the queue size is infinite. The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data). New in version 2.6.
🌐
GeeksforGeeks
geeksforgeeks.org › python › queue-in-python
Queue in Python - GeeksforGeeks
December 11, 2025 - Explanation: popleft() efficiently removes the first element without shifting, making deque ideal for queues. Python’s queue module provides a thread-safe FIFO queue. You can specify a maxsize.
🌐
GitHub
github.com › enthought › Python-2.7.3 › blob › master › Lib › Queue.py
Python-2.7.3/Lib/Queue.py at master · enthought/Python-2.7.3
"""A multi-producer, multi-consumer queue.""" · from time import time as _time · try: import threading as _threading · except ImportError: import dummy_threading as _threading · from collections import deque · import heapq · · __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] ·
Author   enthought
🌐
Real Python
realpython.com › ref › stdlib › queue
queue | Python Standard Library – Real Python
>>> from queue import PriorityQueue >>> q = PriorityQueue() >>> q.put((2, "task1")) >>> q.put((1, "task2")) >>> q.get() (1, 'task2')
🌐
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › queue.html
8.10. Queue — A synchronized queue class — Stackless-Python 2.7.15 documentation
If maxsize is less than or equal to zero, the queue size is infinite. The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data). New in version 2.6.
🌐
Python Module of the Week
pymotw.com › 2 › Queue
Queue – A thread-safe FIFO implementation - Python Module of the Week
It processes items in the queue one after another. These daemon threads go into an infinite loop, and only exit when the main thread ends. """ while True: print '%s: Looking for the next enclosure' % i url = q.get() print '%s: Downloading:' % i, url # instead of really downloading the URL, # we just pretend and sleep time.sleep(i + 2) q.task_done() # Set up some threads to fetch the enclosures for i in range(num_fetch_threads): worker = Thread(target=downloadEnclosures, args=(i, enclosure_queue,)) worker.setDaemon(True) worker.start() # Download the feed(s) and put the enclosure URLs into # the queue.
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()
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 54277946 › queue-between-python2-and-python3
python - Queue between Python2 and Python3 - Stack Overflow
January 20, 2019 - from multiprocessing.managers import BaseManager class QueueManager(BaseManager): pass QueueManager.register('get_queue') m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra') m.connect() queue = m.get_queue() queue.put('hello') With both only in Python3 or in Python2 everything runs perfectly.
🌐
Guru99
guru99.com › home › python › python queue: fifo, lifo example
Python Queue: FIFO, LIFO Example
August 12, 2024 - import queue q1 = queue.LifoQueue() for i in range(20): q1.put(i) # this will additem from 0 to 20 to the queue while not q1.empty(): print("The value is ", q1.get()) # get() will remove the item from the queue. ... The value is 19 The value is 18 The value is 17 The value is 16 The value is 15 The value is 14 The value is 13 The value is 12 The value is 11 The value is 10 The value is 9 The value is 8 The value is 7 The value is 6 The value is 5 The value is 4 The value is 3 The value is 2 The value is 1 The value is 0
🌐
PyPI
pypi.org › project › queuelib
queuelib
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
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...
🌐
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 - from collections import deque dq = deque() dq.append(1) dq.append(2) dq.appendleft(3) print(dq) # deque([3, 1, 2]) dq.pop() # 2 dq.popleft() # 3 · deque provides a thread-safe version called deque.deque that can be used in multi-threaded programs. ... In addition to the built-in data structures, you can also implement a custom queue class in Python.
Top answer
1 of 1
2

Yes. We can Optimize for the time cost of m function calls on your queue. This optimization can be any mix of enqueue and dequeue calls.

Assume you already have a stack implementation and it gives O(1)O(1) time push and pop.

#

#
class Stack():

    def __init__(self):
        self.stk = []

    def pop(self):
        """raises IndexError if you pop when it's empty"""
        return self.stk.pop()

    def push(self, elt):
        self.stk.append(elt)

    def is_empty(self):
        return len(self.stk) == 0

    def peek(self):
        if not self.stk.is_empty():
            return self.stk[-1]


class Queue():

    def __init__(self):
        self.q = Stack()  # the primary queue
        self.b = Stack()  # the reverse, opposite q (a joke: q vs b)
        self.front = None

    def is_empty(self):
        return self.q.is_empty()

    def peek(self):
        if self.q.is_empty():
            return None
        else:
            return self.front

    def enqueue(self, elt):
        self.front = elt
        self.q.push(elt)

    def dequeue(self):
        """raises IndexError if you dequeue from an empty queue"""
        while not self.q.is_empty() > 0:
            elt = self.q.pop()
            self.b.push(elt)
        val = self.b.pop()
        elt = None
        while not self.b.is_empty() > 0:
            elt = self.b.pop()
            self.q.push(elt)
        self.front = elt
        return val


# Now let's test


class TestQueueTwoStacks(unittest.TestCase):

    def setUp(self):
        self.q = Queue()

    def test_queuedequue(self):
        """queue up 5 integers, check they are in there, dequeue them, check for emptiness, perform other blackbox and whitebox tests"""
        self.assertTrue(self.q.is_empty())
        self.assertTrue(self.q.q.is_empty())
        self.assertTrue(self.q.b.is_empty())

        l = range(5)
        for i in l:
            self.q.enqueue(i)

        self.assertEqual(4, self.q.peek())
        self.assertEqual(l, self.q.q.stk)

        s = []
        l.reverse()
        for i in l:
            elt = self.q.dequeue()
            s.append(elt)

        self.assertTrue(self.q.is_empty())
        self.assertTrue(self.q.q.is_empty())
        self.assertTrue(self.q.b.is_empty())

        l.reverse()
        self.assertEqual(s, l)
        self.assertEqual([], self.q.b.stk)
        self.assertEqual([], self.q.q.stk)

if __name__ == "__main__":
    # unittest.main()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestQueueTwoStacks)
    unittest.TextTestRunner(verbosity=2).run(suite)
🌐
Intellipaat
intellipaat.com › home › blog › queue in python – implementation explained
Queue in Python: How to Implement Queue in Python
October 14, 2025 - If the queue is empty, we display a message indicating that the queue is empty. ... If the user enters `’4’`, we display a message indicating that the program is exiting, and then we break out of the loop, ending the program. ... If the user enters an invalid choice (other than `’1’`, `’2’`, `’3’`, or `’4’`), we display a message indicating that the choice is invalid, and the loop continues to prompt the user for another choice.