2012-07-17 68 views
41

我在尝试了解多处理队列如何在python上工作以及如何实现它时遇到了很多麻烦。假设我有两个从共享文件访问数据的python模块,我们称这两个模块为编写器和读者。我的计划是让读写器都将请求放入两个单独的多处理队列中,然后让第三个进程在循环中弹出这些请求并执行。如何在Python中使用多处理队列?

我的主要问题是,我真的不知道如何正确地实现multiprocessing.queue,你不能真正实例化每个进程的对象,因为它们将是单独的队列,你如何确保所有进程与一个共享队列(或在这种情况下,队列)

+3

当您在父进程中实例化它们时,将队列作为参数传递给每个进程类。 – 2012-07-17 04:20:06

回答

57

我的主要问题是,我真的不知道如何正确地实施multiprocessing.queue,你不能真正实例化对象的每一个过程,因为他们将是不同的队列,您如何确保所有进程都与共享队列相关(或者在这种情况下是队列)

这是读写器共享单个队列的一个简单例子......作者向读者发送一串整数;当作者用完数字时,它会发送'DONE',让读者知道跳出读取循环。

from multiprocessing import Process 
from queue import Queue 
import time 

def reader(queue): 
    ## Read from the queue 
    while True: 
     msg = queue.get()   # Read from the queue and do nothing 
     if (msg == 'DONE'): 
      break 

def writer(count, queue): 
    ## Write to the queue 
    for ii in xrange(0, count): 
     queue.put(ii)    # Write 'count' numbers into the queue 
    queue.put('DONE') 

if __name__=='__main__': 
    for count in [10**4, 10**5, 10**6]: 
     queue = Queue() # reader() reads from queue 
          # writer() writes to queue 
     reader_p = Process(target=reader, args=((queue),)) 
     reader_p.daemon = True 
     reader_p.start()  # Launch reader() as a separate python process 

     _start = time.time() 
     writer(count, queue) # Send a lot of stuff to reader() 
     reader_p.join()   # Wait for the reader to finish 
     print "Sending %s numbers to Queue() took %s seconds" % (count, 
      (time.time() - _start)) 
+6

很好的例子。就像解决OP的混乱问题一样,还有一点信息......这个例子表明共享队列需要源自主进程,然后传递给它的所有子进程。为了使两个完全不相关的进程共享数据,它们必须通过一些中央或相关网络设备(例如套接字)进行通信。有些事情必须协调这些信息。 – jdi 2012-07-17 05:28:38

+4

很好的例子..我也是新来这个主题..如果我有多个进程运行相同的目标函数(不同的参数),如何确保他们不会冲突,而把数据放入队列..是锁必要? – WYSIWYG 2014-01-04 17:26:35

+0

@bharat_iyengar从多处理模块文档中可以看出,使用几个锁/信号量来实现Queue。所以,当你使用get()和put(对象)队列方法时,如果其他进程/线程正在尝试获取或在队列中放置某些东西,队列将会阻塞。所以你不必担心手动锁定它。 – almel 2014-06-05 22:01:58

1

在“from queue import Queue”中没有模块叫做queue,而应该使用多处理。因此,它应该看起来像“从多处理进口队列”

+0

https://docs.python.org/3/library/queue.html – Jakub 2018-02-05 13:59:19