Python 2.7: Multiprocessing: How to not block whilst using a queue for communication
Question: I am using a Queue for communicating between processes and also an event flag
to indicate whether or not the parent process wants to exit however the Queue
in child process is in a blocked state, waiting for more input.

I can make the queue not block by using get_nowait() however that is making
the processor use 100%

What is the recommended way of being able to close a child process and accept
input at the same time?

    
    
    from multiprocessing import Process
    from multiprocessing import Event
    from multiprocessing import Queue
    
    class EchoProcess(Process):
    
        def __init__(self, iQ, closeEvent):
            Process.__init__(self)
            self.iQ = iQ
            self.closeEvent = closeEvent
    
        def run(self):
            while not self.closeEvent.is_set():
                istring = self.iQ.get()
                print(istring)
            print("exited")
    
    if __name__ == "__main__":
        iQ = Queue()
        closeEvent = Event()
        echoProcess = EchoProcess(iQ, closeEvent)
        echoProcess.start()
        while True:
            istring = raw_input("Enter:")
            if istring == "quit": break
            iQ.put(istring)
        closeEvent.set()
    


Answer: You can use a sentinel.

Define the sentinel as a value that never appears in normal data and when
EchoProcess gets it, it quits.

For example:

    
    
    from multiprocessing import Process
    from multiprocessing import Queue
    
    class Sentinel(object): pass
    
    class EchoProcess(Process):
    
        def __init__(self, iQ):
            Process.__init__(self)
            self.iQ = iQ
    
        def run(self):
            for istring in iter(iQ.get, Sentinel):
                print(istring)
            print("exited")
    
    if __name__ == "__main__":
        iQ = Queue()
        echoProcess = EchoProcess(iQ)
        echoProcess.start()
        while True:
            istring = raw_input("Enter:")
            if istring == "quit": break
            iQ.put(istring)
        iQ.put(Sentinel)
        echoProcess.join()
    

