Python readings – Process and Queue

#!/usr/bin/python
from multiprocessing import Process, Queue
import time
import sys

def Worker(queue):
    
    while(True):
        if not queue.empty():
            msg = queue.get()
            print msg    
        else:
            time.sleep(1)
            sys.stdout.write('#')
            sys.stdout.flush()



if __name__ == "__main__":
    queue = Queue()
    worker = Process(target=Worker, args=((queue),))
    worker.daemon = True
    worker.start()
        
    while(True):
        mesg = raw_input("Enter to print:")
        queue.put(mesg)

Although the output does not seem to give any meaningful understanding the way it is printed, just to give a
a rough idea about the flow. The code waits for user input until “enter” is pressed.
Meanwhile the worker thread keeps checking for queue messages and when empty prints “#” and wait for a second
WHen the enter is pressed the user input is fed to the queue and it is printed by the worker process.

Enter to print:##AAAA#
Enter to print:#AAAA
######

Leave a Reply

Your email address will not be published. Required fields are marked *