如何在Python中“监听”多处理队列

时间:2013-05-15 17:00:25

标签: python python-2.7 queue multiprocessing

我将从代码开始,我希望它足够简单:

import Queue
import multiprocessing


class RobotProxy(multiprocessing.Process):

    def __init__(self, commands_q):
        multiprocessing.Process.__init__(self)

        self.commands_q = commands_q


    def run(self):
        self.listen()
        print "robot started"


    def listen(self):

        print "listening"
        while True:
            print "size", self.commands_q.qsize()
            command = self.commands_q.get()
            print command
            if command is "start_experiment":
                self.start_experiment()
            elif command is "end_experiment":
                self.terminate_experiment()
                break
            else: raise Exception("Communication command not recognized")
        print "listen finished"


    def start_experiment(self):
        #self.vision = ds.DropletSegmentation( )
        print "start experiment"


    def terminate_experiment(self):
        print "terminate experiment"



if __name__ == "__main__":

    command_q = Queue.Queue()
    robot_proxy = RobotProxy( command_q )
    robot_proxy.start()
    #robot_proxy.listen()
    print "after start"
    print command_q.qsize()
    command_q.put("start_experiment")
    command_q.put("end_experiment")
    print command_q.qsize()

    raise SystemExit

所以基本上我启动了一个进程,我希望这个进程能够监听放在队列中的命令。

当我执行此代码时,我得到以下内容:

after start
0
2
listening
size 0

似乎我没有正确地共享队列,或者我正在做任何其他错误。当理论上队列有2个元素

时,程序会永远停留在“self.commands_q.get()”中

1 个答案:

答案 0 :(得分:5)

您需要使用multiprocessing.Queue而不是Queue.Queue,以便跨进程共享Queue对象。

见这里:Multiprocessing Queues