Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Multiprocessing queue

I am populating a queue with a set of jobs that I want to run in parallel and using python's multiprocessing module for doing that. Code snippet below:

import multiprocessing
from multiprocessing import Queue
queue = Queue()
jobs = [['a', 'b'], ['c', 'd']]
for job in jobs:
    queue.put(job)

When I do queue.get() I get the following:

['a', 'b']

Why is the queue not getting populated with all the jobs?

like image 361
Kaushik Balamukundhan Avatar asked Mar 31 '11 20:03

Kaushik Balamukundhan


People also ask

What is multiprocessing queue in Python?

Python multiprocessing Queue classQueues are specially useful when passed as a parameter to a Process' target function to enable the Process to consume data. By using put() function we can insert data to then queue and using get() we can get items from queues. See the following code for a quick example.

How do queues relate to multiprocessing?

A queue is a data structure on which items can be added by a call to put() and from which items can be retrieved by a call to get(). The multiprocessing. Queue provides a first-in, first-out FIFO queue, which means that the items are retrieved from the queue in the order they were added.

Is Python queue process safe?

Queues are thread and process safe. This means that processes may get() and put() items from and to the queue concurrently without fear of a race condition. You can learn more about to how to use queues with multiple processes in the tutorial: Multiprocessing Queue in Python.

Is Python queue slow?

queue is too slow putting and getting elements to transfer data between python processes. But if you put or get one list with elements work similar as put or get one single element; this list is getting as fast as usually but this has too many elements for process in the subprocess and this action is very quickly.


1 Answers

The queue is actually geting populated. You need to call queue.get() for each time you put an object to the queue. So you just need to call queue.get() one more time.

>>> import multiprocessing
>>> from multiprocessing import Queue
>>> queue = Queue()
>>> jobs = [['a', 'b'], ['c', 'd']]
>>> for job in jobs:
    queue.put(job)


>>> queue.get()
['a', 'b']
>>> queue.get()
['c', 'd']
like image 59
Utku Zihnioglu Avatar answered Oct 04 '22 18:10

Utku Zihnioglu