如何在 Python 中"listen"到多处理队列



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

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

我启动了一个进程,我想让这个进程监听放在Queue上的命令。

当我执行这段代码时,我得到以下结果:

after start
0
2
listening
size 0

似乎我没有正确地共享队列,或者我正在做任何其他错误。程序会永远卡在self.commands_q.get()中,而理论上队列有2个元素

您需要使用多处理。Queue而不是Queue。队列,以便在进程之间共享Queue对象。

查看这里:多处理队列

最新更新