python多处理将子进程中的di​​ct传递回父进程

时间:2011-12-20 19:32:57

标签: python variables queue multiprocessing

我有一个子进程函数(称为parseContents),它使用以下代码调用:

def main():
   p = Process(target=parseContents, args=(event.name,))
   p.start()
   p.join()

利用多处理模块和Queue方法,我如何将一个变量从parseContents传递回main,以便在p.join()行之后使用?

我读过我会用:

  from multiprocessing import Queue
  queue = Queue()
  queue.put( myVar ) #obviously this would be inside parseContents()
  print queue.get( myVar )  #obviously this would be inside main()

在我的main中调用它后,是否需要将'queue'变量/实例传递给我的parseContents函数,以便子进程知道队列?

在上面的main():段中构建的父进程和子进程之间的多处理队列的正确实现是什么?

1 个答案:

答案 0 :(得分:1)

要以这种方式使用队列,您必须在main()中对其进行实例化,并将其作为参数传递给parseContents。一旦你这样做,你应该能够使用你拥有的代码(在正确的位置)将项目从子进程传递到父进程。

Python文档警告说,如果Queue不为空,则不应尝试加入子进程,因此在调用join之前,请确保将所有项目从队列中取出。实际上,您应该能够在不调用join的情况下运行代码,因为queue.get将等到队列中有项目。