If I use Queue.Queue
, then my read()
function doesn't work, why? But if I use multiprocessing.Queue
, it works well:
from multiprocessing import Pool, Process, Queue
import os, time
# from Queue import Queue
def write(q):
for v in ['A', 'B', 'C']:
print 'Put %s to queue ' % v
q.put_nowait(v)
time.sleep(0.2)
def read(q):
while 1:
if not q.empty():
v = q.get(True)
print "Get %s from queue" % v
time.sleep(0.2)
else:
break
if __name__ == '__main__':
q = Queue()
pw = Process(target=write, args=(q, ))
pr = Process(target=read, args=(q, ))
pw.start()
pw.join()
pr.start()
pr.join()
print "all done..."
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.
A simple way to communicate between process with multiprocessing is to use a Queue to pass messages back and forth. Any pickle-able object can pass through a Queue. This short example only passes a single message to a single worker, then the main process waits for the worker to finish.
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.
A multiprocessing. Event object wraps a boolean variable that can either be “set” (True) or “not set” (False). Processes sharing the event instance can check if the event is set, set the event, clear the event (make it not set), or wait for the event to be set.
Queue.Queue
is just an in-memory queue that knows how to deal with multiple threads using it at the same time. It only works if both the producer and the consumer are in the same process.
Once you have them in separate system processes, which is what the multiprocessing
library is about, things are a little more complicated, because the processes no longer share the same memory. You need some kind of inter-process communication method to allow the two processes to talk to each other. It can be a shared memory, a pipe or a socket, or possibly something else. This is what multiprocessing.Queue
does. It uses pipes to provide a way for two processes to communicate. It just happens to implement the same API as Queue.Queue
, because most Python programmers are already familiar with it.
Also note that the way you are using the queue, you have a race condition in your program. Think about what happens if the write
process writes to the queue right after you call q.empty()
in the read
process. Normally you would add some special item to the queue (e.g. None
) which would mean that the consumer can stop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With