Short Summary

As of CY2023, the technique described in this answer is quite out of date. These days, use concurrent.futures.ProcessPoolExecutor() instead of multiprocessing, below...

This answer describes the benefits and shortcomings of using concurrent.futures.ProcessPoolExecutor(). FYI, multiple python processes are sometimes used instead of threading to get the most benefit from concurrency. That said, python threading works pretty well as long as there is sufficient CPU activity to avoid the GIL (activity such as sending / receiving network traffic).

Original Answer

My main problem is that I really don't know how to implement multiprocessing.queue correctly, you cannot really instantiate the object for each process since they will be separate queues, how do you make sure that all processes relate to a shared queue (or in this case, queues)

This is a simple example of a reader and writer sharing a single queue... The writer sends a bunch of integers to the reader; when the writer runs out of numbers, it sends 'DONE', which lets the reader know to break out of the read loop.

You can spawn as many reader processes as you like...

from multiprocessing import Process, Queue
import time
import sys


def reader_proc(queue):
    """Read from the queue; this spawns as a separate Process"""
    while True:
        msg = queue.get()  # Read from the queue and do nothing
        if msg == "DONE":
            break


def writer(count, num_of_reader_procs, queue):
    """Write integers into the queue.  A reader_proc() will read them from the queue"""
    for ii in range(0, count):
        queue.put(ii)  # Put 'count' numbers into queue

    ### Tell all readers to stop...
    for ii in range(0, num_of_reader_procs):
        queue.put("DONE")


def start_reader_procs(qq, num_of_reader_procs):
    """Start the reader processes and return all in a list to the caller"""
    all_reader_procs = list()
    for ii in range(0, num_of_reader_procs):
        ### reader_p() reads from qq as a separate process...
        ###    you can spawn as many reader_p() as you like
        ###    however, there is usually a point of diminishing returns
        reader_p = Process(target=reader_proc, args=((qq),))
        reader_p.daemon = True
        reader_p.start()  # Launch reader_p() as another proc

        all_reader_procs.append(reader_p)

    return all_reader_procs


if __name__ == "__main__":
    num_of_reader_procs = 2
    qq = Queue()  # writer() writes to qq from _this_ process
    for count in [10**4, 10**5, 10**6]:
        assert 0 < num_of_reader_procs < 4
        all_reader_procs = start_reader_procs(qq, num_of_reader_procs)

        writer(count, len(all_reader_procs), qq)  # Queue stuff to all reader_p()
        print("All reader processes are pulling numbers from the queue...")

        _start = time.time()
        for idx, a_reader_proc in enumerate(all_reader_procs):
            print("    Waiting for reader_p.join() index %s" % idx)
            a_reader_proc.join()  # Wait for a_reader_proc() to finish

            print("        reader_p() idx:%s is done" % idx)

        print(
            "Sending {0} integers through Queue() took {1} seconds".format(
                count, (time.time() - _start)
            )
        )
        print("")
Answer from Mike Pennington on Stack Overflow
🌐
Python
docs.python.org › 3 › library › multiprocessing.html
multiprocessing — Process-based parallelism
Note that one can also create a shared queue by using a manager object – see Managers. ... multiprocessing uses the usual queue.Empty and queue.Full exceptions to signal a timeout.
Top answer
1 of 7
192

Short Summary

As of CY2023, the technique described in this answer is quite out of date. These days, use concurrent.futures.ProcessPoolExecutor() instead of multiprocessing, below...

This answer describes the benefits and shortcomings of using concurrent.futures.ProcessPoolExecutor(). FYI, multiple python processes are sometimes used instead of threading to get the most benefit from concurrency. That said, python threading works pretty well as long as there is sufficient CPU activity to avoid the GIL (activity such as sending / receiving network traffic).

Original Answer

My main problem is that I really don't know how to implement multiprocessing.queue correctly, you cannot really instantiate the object for each process since they will be separate queues, how do you make sure that all processes relate to a shared queue (or in this case, queues)

This is a simple example of a reader and writer sharing a single queue... The writer sends a bunch of integers to the reader; when the writer runs out of numbers, it sends 'DONE', which lets the reader know to break out of the read loop.

You can spawn as many reader processes as you like...

from multiprocessing import Process, Queue
import time
import sys


def reader_proc(queue):
    """Read from the queue; this spawns as a separate Process"""
    while True:
        msg = queue.get()  # Read from the queue and do nothing
        if msg == "DONE":
            break


def writer(count, num_of_reader_procs, queue):
    """Write integers into the queue.  A reader_proc() will read them from the queue"""
    for ii in range(0, count):
        queue.put(ii)  # Put 'count' numbers into queue

    ### Tell all readers to stop...
    for ii in range(0, num_of_reader_procs):
        queue.put("DONE")


def start_reader_procs(qq, num_of_reader_procs):
    """Start the reader processes and return all in a list to the caller"""
    all_reader_procs = list()
    for ii in range(0, num_of_reader_procs):
        ### reader_p() reads from qq as a separate process...
        ###    you can spawn as many reader_p() as you like
        ###    however, there is usually a point of diminishing returns
        reader_p = Process(target=reader_proc, args=((qq),))
        reader_p.daemon = True
        reader_p.start()  # Launch reader_p() as another proc

        all_reader_procs.append(reader_p)

    return all_reader_procs


if __name__ == "__main__":
    num_of_reader_procs = 2
    qq = Queue()  # writer() writes to qq from _this_ process
    for count in [10**4, 10**5, 10**6]:
        assert 0 < num_of_reader_procs < 4
        all_reader_procs = start_reader_procs(qq, num_of_reader_procs)

        writer(count, len(all_reader_procs), qq)  # Queue stuff to all reader_p()
        print("All reader processes are pulling numbers from the queue...")

        _start = time.time()
        for idx, a_reader_proc in enumerate(all_reader_procs):
            print("    Waiting for reader_p.join() index %s" % idx)
            a_reader_proc.join()  # Wait for a_reader_proc() to finish

            print("        reader_p() idx:%s is done" % idx)

        print(
            "Sending {0} integers through Queue() took {1} seconds".format(
                count, (time.time() - _start)
            )
        )
        print("")
2 of 7
36

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
        msg = Msg(event, args)
        self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-multiprocessing-queue-vs-multiprocessing-manager-queue
Python multiprocessing.Queue vs ...
January 30, 2026 - This code is similar to the previous example, but it demonstrates the use of the manager().Queue() class from the multiprocessing module to communicate between two separate processes.
🌐
Medium
medium.com › @surve.aasim › process-synchronization-using-multiprocessing-queue-4a2702cc6f5e
Process Synchronization using multiprocessing.Queue | by Aasim | Medium
August 17, 2023 - import multiprocessing def ... have completed.") In this example, the producer process populates the queue with items, and the consumer process extracts items from the queue....
🌐
Samuelstevens
samuelstevens.me › writing › python-multiprocessing
Multiprocessing Queue Example in Python
Now we can run time python queue_demo.py and see that it takes less than 30 seconds (3 seconds * 5 elements produced * 2 producers). It’s not perfect (should be exactly 15 seconds), but it’s definitely faster than in a single process. Here’s the final program, licensed under GNU AGPLv3. If you have any improvements/suggestions, I can be reached at samuel.robert.stevens@gmail.com · import time from multiprocessing import Process, Queue def produce(q: "Queue[int]", length: int) -> None: for _ in range(length): q.put(3) q.put(-1) # stop-value def consume(q: "Queue[int]") -> None: while Tru
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-multiprocessing-example
Python Multiprocessing Example: Process, Pool & Queue | DigitalOcean
March 31, 2026 - The example below reproduces one common pattern: a parent joins a child while the child is blocked trying to put into a full queue that the parent never drains. # Tested on Python 3.11 # broken pattern: parent joins before draining the queue import multiprocessing def fill_queue(q, n): for ...
🌐
Super Fast Python
superfastpython.com › multiprocessing-queue-in-python
Multiprocessing Queue in Python – SuperFastPython
May 27, 2022 - You can communicate between processes with queue via the multiprocessing.Queue class. In this tutorial you will discover how to use the process queue in Python.
Find elsewhere
🌐
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 - Here is an example of how to use ... from multiprocessing import Process, Queue def worker(q): print(q.get()) # Get item from queue q.put('Result') # Put result back if __name__ == '__main__': q = Queue() q.put('Input') p = Process(target=worker, args=(q,)) p.start() p.join() print(q.get()) # Print result ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › multiprocessing-python-set-2
Multiprocessing in Python | Set 2 (Communication between processes) - GeeksforGeeks
July 23, 2025 - Communication between processes Effective use of multiple processes usually requires some communication between them, so that work can be divided and results can be aggregated. multiprocessing supports two types of communication channel between processes: ... Queue : A simple way to communicate between process with multiprocessing is to use a Queue to pass messages back and forth.
🌐
Python.org
discuss.python.org › python help
Version of multiprocessing.Queue that works with unrelated processes? - Python Help - Discussions on Python.org
June 11, 2023 - I’m looking for an implementation of a cross-process queue, to pass data between two parts of my app. The only one I can find in the stdlib is multiprocessing.Queue, which requires the two processes be managed by multipr…
🌐
GeeksforGeeks
geeksforgeeks.org › python › multiprocessing-python-set-1
Multiprocessing in Python | Set 1 (Introduction) - GeeksforGeeks
July 23, 2025 - Let us consider another program to understand the concept of different processes running on same python script. In this example below, we print the ID of the processes running the target functions: ... # importing the multiprocessing module import multiprocessing import os def worker1(): # printing process id print("ID of process running worker1: {}".format(os.getpid())) def worker2(): # printing process id print("ID of process running worker2: {}".format(os.getpid())) if __name__ == "__main__": # printing main program process id print("ID of main process: {}".format(os.getpid())) # creating p
🌐
Codemia
codemia.io › home › knowledge hub › how to use multiprocessing queue in python?
How to use multiprocessing queue in Python? | Codemia
September 23, 2025 - A queue follows the First In First Out (FIFO) method, meaning the first element added to the queue will be the first one to be removed. In the context of the multiprocessing module, the Queue object allows multiple processes to read and write. Here's a basic example showing how to set up a queue in a multiprocessing situation:
🌐
GitHub
gist.github.com › prempv › 717270a4470a10146c6776820e8e3cbc
Python code that implements multiprocessing with Task Queues and Result Queues. It creates 5 worker processes, that picks an item from the task list (input_queue), processes it, and adds the result to output_queue. · GitHub
Python code that implements multiprocessing with Task Queues and Result Queues. It creates 5 worker processes, that picks an item from the task list (input_queue), processes it, and adds the result to output_queue. - Python Multiprocess with Task List.py
🌐
Medium
martinxpn.medium.com › multiprocessing-in-python-72-100-days-of-python-db0e9c66b0b3
Multiprocessing in Python (72/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - Additionally, using queues can help balance the load between processes, by allowing a single producer to feed multiple consumers or vice versa. Multiprocessing pipes are another communication mechanism provided by the multiprocessing module in Python.
🌐
Daily.dev
app.daily.dev › home › digitalocean community › python multiprocessing example: process, pool & queue
Python Multiprocessing Example: Process, Pool & Queue | daily.dev
April 1, 2026 - Comprehensive walkthrough of Python's multiprocessing module covering Process, Pool, Queue, Pipe, Lock, Value, Array, and Manager primitives. Explains why...
🌐
Super Fast Python
superfastpython.com › multiprocessing-pool-share-queue
How to Share a Queue with a Multiprocessing Pool – SuperFastPython
March 3, 2023 - For example, a task function may declare the "queue" global variable before making use of it. # task completed in a worker def task(): # declare the queue global variable global queue # ... And that's it. You can learn more about forked child processes inheriting global variables in the tutorial: ...
🌐
GitHub
gist.github.com › wrunk › b689be4b59270c32441c
Python multiprocessing pool with queues · GitHub
Python multiprocessing pool with queues. GitHub Gist: instantly share code, notes, and snippets.
🌐
TestDriven.io
testdriven.io › blog › developing-an-asynchronous-task-queue-in-python
Developing an Asynchronous Task Queue in Python | TestDriven.io
June 21, 2023 - This tutorial looks at how to implement several asynchronous task queues using the Python multiprocessing library and Redis.
🌐
Mimo
mimo.org › glossary › python › multiprocessing
Python Multiprocessing: Syntax, Usage, and Examples
Logging across multiple processes can be tricky, but multiprocessing.Queue() helps.
🌐
Plain English
python.plainenglish.io › python-tutorial-42-python-multiprocessing-process-pool-queue-4e59b7f01023
Python Tutorial 42 — Python Multiprocessing: Process, Pool, Queue | by Ayşe Kübra Kuyucu | Python in Plain English
April 16, 2024 - In this tutorial, you will learn how to create and use processes for parallel execution using the multiprocessing module in Python. You will also learn how to use pool and map for parallel execution, how to use queue for inter-process communication, and how to handle exceptions and terminate processes.