我的问题是:

我有3个proc,想要共享从同一个类和几个队列加载的配置。我想生成另一个proc作为multiprocessing.manager来共享这些信息。

我该怎么做?有人可以购买示例代码,避免使用全局变量并使用多处理管理器类吗?

Python文档并没有那么有用: - (

有帮助吗?

解决方案

我找到了这个的特定部分。 Python多处理文档很有帮助。以下程序:

from multiprocessing import Process, Queue, current_process
import time

def f(q):
    name = current_process().name
    config = q.get()
    print "%s got config: %s" % (name, config)
    print "%s beginning processing at %s" % (name, time.asctime())
    time.sleep(5)
    print "%s completing processing at %s" % (name, time.asctime())

if __name__ == '__main__':
    q = Queue()
    processes = []
    cfg = { 'my' : 'config', 'data' : 'here' }
    for i in range(3):
        p = Process(target=f, args=(q,))
        processes.append(p)
        p.start()
        q.put(cfg)

    for p in processes:
        p.join()

演示了主脚本(在您的问题中是“多处理管理器”),创建了3个进程,并为每个进程发送了一个配置(此处显示为字典)。

每个进程读取配置,进行处理(此处,只是休眠5秒)然后终止。运行此脚本的输出是:

Process-1 got config: {'my': 'config', 'data': 'here'}
Process-1 beginning processing at Tue Jun 23 23:34:23 2009
Process-2 got config: {'my': 'config', 'data': 'here'}
Process-2 beginning processing at Tue Jun 23 23:34:23 2009
Process-3 got config: {'my': 'config', 'data': 'here'}
Process-3 beginning processing at Tue Jun 23 23:34:23 2009
Process-1 completing processing at Tue Jun 23 23:34:28 2009
Process-2 completing processing at Tue Jun 23 23:34:28 2009
Process-3 completing processing at Tue Jun 23 23:34:28 2009
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top