2

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

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()”中

4

1 回答 1

5

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

请参见此处:多处理队列

于 2013-05-15T17:10:52.473 回答