如何在 Python 进程之间共享数据?

问题描述

我正在使用多处理为我的 Python 应用程序创建一个子进程.我想在我的父进程和子进程之间共享数据.需要说明的是,我需要异步共享这个,也就是说子进程和父进程会在代码运行期间更新数据.

I'm using multiprocessing to create a sub-process to my Python app. I would like to share data between my parent process and the child process. it's important to mention that I need to share this asynchronously, means that the child process and the parent process will update the data during the code running.

最好的方法是什么?


解决方案

这是python文档中的一个简单示例 -

This is one simple example from python documentation -

from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print q.get()    # prints "[42, None, 'hello']"
    p.join()

你也可以使用管道,有关详细信息,请参阅 - https://docs.python.org/2/library/multiprocessing.html

You can use pipe as well, Refer for more details - https://docs.python.org/2/library/multiprocessing.html

相关文章