Python 多进程管理器

3 投票
1 回答
2994 浏览
提问于 2025-04-15 12:27

我的问题是:

我有三个进程,它们想要共享从同一个类加载的配置和几个队列。我想再启动一个进程,作为一个多进程管理器来共享这些信息。

我该怎么做呢?有没有人能提供一个示例代码,避免使用全局变量,并利用多进程管理器类?

Python的文档对我帮助不大 :-(

1 个回答

3

我发现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

撰写回答