gpt4 book ai didi

python multiprocessing 将字典从子进程传递回父进程

转载 作者:行者123 更新时间:2023-11-28 18:53:18 25 4
gpt4 key购买 nike

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

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

利用 multiprocessing 模块和 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 中调用它之后,我是否需要将“队列”变量/实例传递给我的 parseContents 函数,以便子进程知道队列?

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

最佳答案

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

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

关于python multiprocessing 将字典从子进程传递回父进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8580883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com