如果我使用 Queue.Queue
,那么我的 read()
函数不起作用,为什么?但是,如果我使用 multiprocessing.Queue
,它运行良好:
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..."
最佳答案
Queue.Queue
只是一个内存队列,它知道如何处理同时使用它的多个线程。它仅在生产者和消费者都在同一进程中时才有效。
一旦你将它们放在单独的系统进程中,这就是 multiprocessing
库的目的,事情就会稍微复杂一些,因为进程不再共享相同的内存。您需要某种进程间通信方法来允许两个进程相互通信。它可以是共享内存、管道或套接字,或者可能是其他东西。这就是 multiprocessing.Queue
所做的。它使用管道为两个进程提供一种通信方式。它恰好实现了与 Queue.Queue
相同的 API,因为大多数 Python 程序员已经熟悉它。
另请注意,您使用队列的方式在您的程序中存在竞争条件。想一想如果在 read
进程中调用 q.empty()
之后 write
进程立即写入队列会发生什么。通常,您会向队列中添加一些特殊项目(例如 None
),这意味着消费者可以停止。
关于python - multiprocessing.Queue 和 Queue.Queue 有什么不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294571/