Queue
- Python course
- Expert
- Lesson 27/47
- 5 min
Learn inter-process queue with multiprocessing.Queue.
What is multiprocessing.Queue?
multiprocessing.Queue is a thread-safe FIFO queue for passing data between processes. You put data with .put() and get it with .get().
Multiple processes can write to and read from the same queue; internal locking guarantees ordering. This is the most common way to send a process's result back to the main program. For example a worker process does q.put(result) and the main program receives it with q.get(). If the queue is empty get waits until data arrives.
Passing data with Queue
A Queue can be used by both the main program and a worker process. The worker puts a result with q.put(result) and the main program gets it with q.get().
The key point: the Queue is passed to the process as an argument. You pass it by writing Process(target=worker, args=(q,)). The worker writes to this queue and the main program reads from it. The queue is FIFO so the first item put is the first taken. If multiple workers write to the same queue the order depends on write speed; but each item is taken only once.
Practice Pass values with Queue
Import with from multiprocessing import Queue. Create a queue with q = Queue(). Put two values with q.put("bir") and q.put("iki"). Get the two values in order with q.get() and print them.
Starter code
# create a queue
# put two values and get them in order
# print themSample solution
from multiprocessing import Queue
q = Queue()
q.put("bir")
q.put("iki")
print(q.get())
print(q.get())Expected output
bir iki
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Queue call
from multiprocessing import ____
q = Queue()
from multiprocessing import Queue
q = Queue()
Explanation: Queue is the inter-process queue.
2 What does q.get() do?
q = Queue()
q.put(42)
val = q.get()- Puts a value into the queue
- Takes a value from the queue Correct answer
- Deletes the queue
- Returns the queue size
Explanation: get() takes a value from the front of the queue.
3 Match Queue concepts
| Term | Meaning |
|---|---|
put |
Puts a value |
get |
Takes a value |
Queue |
FIFO queue |
args=(q,) |
Passes the queue |