Python 多处理池队列通信

MaX*_*MaX 3 python multiprocessing python-2.7

我正在尝试实现一个由两个并行运行并通过队列进行通信的进程组成的池。

目标是让写入进程使用队列将消息传递给读取进程。

每个进程都在终端上打印反馈以便获得反馈。

这是代码:

#!/usr/bin/env python

import os
import time
import multiprocessing as mp
import Queue

def writer(queue):
    pid = os.getpid()
    for i in range(1,4):
        msg = i
        print "### writer ", pid, " -> ", msg
        queue.put(msg)
        time.sleep(1)
        msg = 'Done'
    print '### '+msg
    queue.put(msg)

def reader(queue):
    pid = os.getpid()
    time.sleep(0.5)
    while True:
        print "--- reader ", pid, " -> ",
        msg = queue.get()
        print msg
        if msg == 'Done':
            break

if __name__ == "__main__":
    print "Initialize the experiment PID: ", os.getpid()
    mp.freeze_support()

    queue = mp.Queue()

    pool = mp.Pool()
    pool.apply_async(writer, (queue)) 
    pool.apply_async(reader, (queue))

    pool.close()
    pool.join()
Run Code Online (Sandbox Code Playgroud)

我期待的输出应该是这样的:

Initialize the experiment PID: 2341
writer 2342 -> 1
reader 2343 -> 1
writer 2342 -> 2
reader 2343 -> 2
writer 2342 -> 3
reader 2343 -> 3
Done
Run Code Online (Sandbox Code Playgroud)

但是我只得到了这条线:

Initialize the experiment PID: 2341
Run Code Online (Sandbox Code Playgroud)

然后脚本退出。

在通过队列进行通信的池中实现两个进程的进程间通信的正确方法是什么?

mas*_*nun 6

我用作mp.Manager().Queue()队列,因为我们不能直接通过Queue。尝试直接使用Queue会导致异常,但由于我们使用apply_async.

我将您的代码更新为:

#!/usr/bin/env python

import os
import time
import multiprocessing as mp
import Queue

def writer(queue):
    pid = os.getpid()
    for i in range(1,4):
        msg = i
        print "### writer ", pid, " -> ", msg
        queue.put(msg)
        time.sleep(1)
        msg = 'Done'
    print '### '+msg
    queue.put(msg)

def reader(queue):
    pid = os.getpid()
    time.sleep(0.5)
    while True:
        print "--- reader ", pid, " -> ",
        msg = queue.get()
        print msg
        if msg == 'Done':
            break

if __name__ == "__main__":
    print "Initialize the experiment PID: ", os.getpid()
    manager = mp.Manager()

    queue = manager.Queue()

    pool = mp.Pool()
    pool.apply_async(writer, (queue,))
    pool.apply_async(reader, (queue,))

    pool.close()
    pool.join()
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出:

Initialize the experiment PID:  46182
### writer  46210  ->  1
--- reader  46211  ->  1
### writer  46210  ->  2
--- reader  46211  ->  2
### writer  46210  ->  3
--- reader  46211  ->  3
### Done
--- reader  46211  ->  Done
Run Code Online (Sandbox Code Playgroud)

我相信这是你所期望的。